I’ve made a working regexp, but i think it’s 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’ve found that (?: ... ) in regexps – means ignoring group match, thus:
el.replace(/(?:<div.*>)(\d+)(?:<\/div>)/g, '<b>$1</b>');
// returns <b>123</b>
but i need an expecting result from 1st example.
Is there a way to exclude ’em? just to write replace(/.../, '<b>$1</b>')?
This is just a little case for understanding how to exclude groups in regexp. And i know, what we can’t parse HTML with regexp 🙂
So you want to get the same result while only using the replacement
<b>$1</b>?In your case just
replace(/\d+/, '<b>$&</b>')would suffice.But if you want to make sure there are div tags around the number, you could use lookarounds and
\Klike in the following expression. Except that JS does not support lookbehind nor\K, so you’re out of luck, you have to use a capturing group for that in JS.