Home > database >  Is there any way to add number separated in html using regex and jquery?
Is there any way to add number separated in html using regex and jquery?

Time:05-06

I want to add a specific number to all the numbers that are separated by commas in HTML using regex and jquery.

here is my trial code -

$('#u-g-wb-break-word').text(function(i, s) {
  return s.replace(/\d /g, function(m) {
    return parseInt(m, 10)   612;
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="u-g-wb-break-word">
  123,451,45.00
</div>

This does work but not in the case of float numbers, In decimal numbers, the script is adding the value after decimal too. To change this I also used /m instead of 'g' but still, it's only working for one number and not all the numbers are separated by commas.

$('#u-g-wb-break-word').text(function(i, s) {
  return s.replace(/\d /m, function(m) {
    return parseInt(m, 10)   612;
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="u-g-wb-break-word">5000.1000</div>

The above code is working but only if I put a single number in the HTML, How can I fix the code. Thanks in advance

CodePudding user response:

Use a regular expression that matches numbers with an optional fraction. Use capture groups to get the integer part and the fraction separately, then just add to the integer.

$('#u-g-wb-break-word').text(function(i, s) {
  return s.replace(/(\d )(\.\d )?/g, function(m, int, fraction) {
    return (parseInt(int)   612)   (fraction || "");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="u-g-wb-break-word">
  123,451,45.00
</div>

  • Related