JSFiddle - React, Tailwind, and code Playground
by Tyler Eich
HTML
<div class="header">
<h1>Time is Money</h1>
<p> Find out how much time it will take you to buy something!</p>
</div>
<div class="test">$12</div>
<ul>
<li>$12</li>
<li>$14.93</li>
<li>$2</li>
<li>$dollars</li>
<li>14.99</li>
<li>$12,001.098</li>
</ul>
CSS
body {
font-family: Helvetica, Arial, sans-serif;
}
h1{
font-size: 30px;
color: green;
}
p {
font-size: 18px;
}
JavaScript
function dollarChange(match, p0, p1, p2, offset, string) {
// pN = Nth in-parentheses match
// Remove commas (reinjected later)
var hasComma = (p1.indexOf(',') > -1);
if (hasComma) p1 = p1.replace(',', '');
// Get decimal precision
var precision = 0;
if (p2) {
p1 = p1 + p2;
precision = p2.length - 1;
}
// Process number
p1 = Number(p1);
var value = p0 + (p1 * 2).toFixed(precision);
// Inject commas if previously found
if (hasComma) {
var parts = value.toString().split('.');
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
value = parts.join('.');
}
return value;
}
// Execute replacement
document.body.innerHTML =
document.body.innerHTML.replace(/([$])([\d,]+)(\.[\d]+)?/g,
dollarChange);