Nishanth Matha Nishanth Matha - 9 months ago 52
Javascript Question

arithmetic operation on regex group javascript

Fairly straight forward question: Is there a way to perform arithmetic operation on a matched group in regex in JS.

Ex: I have string:

<img style="top:200">

I want to replace 200 or whatever number by dividing by 5, which would be 40 in this case. So output:

<img style="top:40">

I tried:

var d= c.replace(/top:([-]?\d*[\.]?\d*)/,'int:'+parseInt($1/5)+'px')

But I get

<img style="top:NaNpx">


You can use a callback function with String#replace method.

var c = '<img style="top:40">';

var d = c.replace(/top:([-]?\d*[\.]?\d*)/, function(m, m1) {
  return 'top:' + m1 / 5 + 'px';


FYI : But it's a bad idea to use regex to parse HTML.

Another method with DOMParser where applying the replace method only for the style attribute value instead of applying to the entire string.

var c = '<img style="top:200">';

var parser = new DOMParser();

var img = parser.parseFromString(c, "text/html")

img.setAttribute('style', img.getAttribute('style').replace(/\btop:([-]?\d*(\.\d+)?)/, function(m, m1) {
  return 'top:' + m1 / 5 + 'px';