ドルの値を持つノードだけを再帰またはループする必要があります。または でまたはreplace()
RegExp を使用しないでください。これにより、ターゲット ページが破棄されるだけでなく、目的の結果が得られるまでに時間がかかります。.html()
innerHTML
DOM メソッドを使用してページを再帰します。通貨値にはさまざまな形式があるため、変換が複雑になる可能性があることに注意してください。
ページ全体 (iframeを除く) の適度に堅牢なコードを次に示します。
// ==UserScript==
// @name _Global currency converter, dollars to rupees
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @grant GM_xmlhttpRequest
// ==/UserScript==
GM_xmlhttpRequest ( {
method: "GET",
url: 'http://rate-exchange.appspot.com/currency?from=USD&to=INR',
//Google sends malformed response, not JSON.
//url: 'http://www.google.com/ig/calculator?hl=en&q=1usd=?inr',
onload: function (rsp){
var rspJSON = JSON.parse (rsp.responseText);
var convRate = rspJSON.rate;
console.log (rspJSON, convRate);
changeDollarsToRupees (document.body, convRate);
}
} );
function changeDollarsToRupees (node, convRate) {
if (node.nodeType === Node.TEXT_NODE) {
if (/\$/.test (node.nodeValue) ) {
processTextNode (node, convRate);
}
}
else if (node.nodeType === Node.ELEMENT_NODE) {
for (var K = 0, numNodes = node.childNodes.length; K < numNodes; ++K) {
changeDollarsToRupees (node.childNodes[K], convRate);
}
}
}
function processTextNode (node, convRate) {
/*-- Results like:
["Three values: ", "$1.10", " ", "$2.20", " ", "$3.00.", ""]
*/
var moneySplit = node.nodeValue.split (/((?:\+|\-)?\$[0-9.,]+)/);
if (moneySplit && moneySplit.length > 2) {
/*-- Money values will be odd array index, loop through
and convert all.
*/
for (var J = 1, L = moneySplit.length; J < L; J += 2) {
var dolVal = parseFloat (moneySplit[J].replace (/\$|,|([.,]$)/g, "") );
if (typeof dolVal === "number") {
//var rupVal = "Rs" + Math.round (dolVal * convRate);
var rupVal = "Rs" + (dolVal * convRate).toFixed (2);
}
else {
var rupVal = moneySplit[J] + " *Err*";
}
moneySplit[J] = rupVal;
}
//-- Rebuild and replace the text node with the changed value (s).
var newTxt = moneySplit.join ("");
node.nodeValue = newTxt;
}
}
これが数ページだけの場合は、jQuery を使用するか、document.querySelectorAll()
関心のある要素だけを処理します。次に例を示します。
var targElements = document.querySelectorAll ("div.priceTable");
for (var J = targElements.length - 1; J >= 0; --J) {
changeDollarsToRupees (targElements[J], convRate);
}