JSFiddle - React, Tailwind, and code Playground
HTML
<button>Convert Dollars</button>
<p> <span class="foo">Price 1 = $1</span>
<a href="#">Price 2: $2.0</a>
<span class="bar">Before $1.1 after.</span>
</p>
<p>Two values: $1.10 and $2.20.</p>
<p>Three values: $1.10 $2.20 $3.00.</p>
<table class="merchandise">
<tr><th>Item</th> <th>Price</th> </tr>
<tr><td>Doodad</td> <td>$0.10</td> </tr>
<tr><td>Widget</td> <td>$2</td> </tr>
<tr><td>Thingamabob</td><td>+$1.0</td> </tr>
<tr><td>Dog race</td> <td>-$7.00</td> </tr>
<tr><td>Mortgage</td> <td>-$13,666.50</td></tr>
<tr><td>{na}</td> <td>$</td> </tr>
</table>
CSS
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid lightgreen;
padding: 1ex;
}
JavaScript
var convRate = 3.33; // Will be reset by AJAX, below.
$.ajax ( {
type: 'GET',
url: 'http://rate-exchange.appspot.com/currency?from=USD&to=INR',
dataType: "jsonp",
crossDomain: true,
success: function (D) {convRate = D.rate;},
timeout: 5000,
error: function (jqXHR, textStatus, errorThrown) {
console.log (errorThrown);
}
} );
$("button").click ( function () {
changeDollarsToRupees (document.body, convRate);
$(this).text ("Done.");
} );
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;
}
}