I want to add a specific number to a number in HTML div separated with commas, another variation of this Is there any way to add number separated in html using regex and jquery?
Here is my trial code:
<div id="u-g-wb-break-word">150,452,032.32</div>
<div id="u-g-wb-break-word">455,666.67</div>
<div id="u-g-wb-break-word">977,435,787.992</div>
var a=$('#u-g-wb-break-word').text();
a=a.replace(/\,/g,'');
a=parseInt(a,10) + 17000;
console.log(a);
$('#u-g-wb-break-word').text(function(i, s) {
return numberWithCommas(s.replace(/^[0-9,]*/g, a));
});
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
I am getting my desired output but only for the first div with one number.
the output of the above code is -
150,469,032.32
455,666.67
977,435,787.992
But I want to add it to every number. Is there any way to perform it in one regex? As mentioned in the above question link. If not what is the best way to do it. Thanks in Advance.
It is better to use class, not id, as id must be unique within document:
$('.u-g-wb-break-word').text((i, s) => new Intl.NumberFormat().format(parseFloat(s.replaceAll(',',''))+1700));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="u-g-wb-break-word">150,452,032.32</div>
<div class="u-g-wb-break-word">455,666.67</div>
<div class="u-g-wb-break-word">977,435,787.992</div>