RegExp: how to exclude matched groups from $ N?

I created a working regex, but I think this is not the best use case:

el = '<div style="color:red">123</div>';
el.replace(/(<div.*>)(\d+)(<\/div>)/g, '$1<b>$2</b>$3');
// expecting result: <div style="color:red"><b>123</b></div>


After googling, I found that (?: ... )

in regexes means ignoring the group match, thus:

el.replace(/(?:<div.*>)(\d+)(?:<\/div>)/g, '<b>$1</b>');
// returns <b>123</b>


but I want the expected result from the first example.

Is there a way to exclude them? just write replace(/.../, '<b>$1</b>')


This is just a small case for understanding how to exclude groups in regexp. And I know that we cannot parse HTML with regex :)


source to share

2 answers

So, you want to get the same result, just using replacement <b>$1</b>


Enough in your case replace(/\d+/, '<b>$&</b>')


But if you want to make sure there are div tags around the number, you can use lookarounds and \K

like in the following expression. Except that JS does not support lookbehind or \K

, so out of luck, you need to use a capture group for the JS.





There is nothing wrong with replacing a value '$1<b>$2</b>$3'

. I would just change your regex to this:

el = '<div style="color:red">123</div>';
el.replace(/(<div[^>]*>)(\d+)(<\/div>)/g, '$1<b>$2</b>$3');


Changing how it matches the first div keeps a complete match in the div tags, but ensures that it matches the minimum before the >

first div is closed , not the maximum possible.

With your regex, you won't get what you want with this input string:

el = '<div style="color:red">123</div><div style="color:red">456</div>';


The problem is using something like:

el.replace(/\d+/, '<b>$&</b>')


- it doesn't work properly with things like this:

el = '<div style="margin-left: 10px">123</div>'


because it picks up numbers inside a div tag.



All Articles