Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$('#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

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading