Saturday, 17 August 2013

JS: Add commas to a string

JS: Add commas to a string

I'm trying to add commas to a string and show that into label through
following function :
HTML :
<input type="text" onkeyup="addCommas(this.value);" /> <br /><br />
<label id="result">Result: </label>
JS
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
var result = x1 + x2;
document.getElementById('result').value = result;
}
JsFiddle
But won't show the result into label.
What am i doing wrong?

No comments:

Post a Comment