You need to recurse or loop through just the nodes that have the dollar values. Never use replace()
or RegExp on .html()
or innerHTML
. Not only will this trash the target page, but you will have a devil of a time getting the desired results.
Recurse through the page using DOM methods. Note that currency values come in many formats, so converting them can get complex.
Here's moderately robust code for the whole page (sans iframes) You can see it in action at jsFiddle:
// ==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;
}
}
If this is just for a few pages, use jQuery or document.querySelectorAll()
to process just the elements you are interested in. For example:
var targElements = document.querySelectorAll ("div.priceTable");
for (var J = targElements.length - 1; J >= 0; --J) {
changeDollarsToRupees (targElements[J], convRate);
}