Javascript – How to replace captured groups only

javascriptregex

I have HTML code before and after the string:

name="some_text_0_some_text"

I would like to replace the 0 with something like : !NEW_ID!

So I made a simple regex :

.*name="\w+(\d+)\w+".*

But I don't see how to replace exclusively the captured block.

Is there a way to replace a captured result like ($1) with some other string ?

The result would be :

name="some_text_!NEW_ID!_some_text"

Best Answer

A solution is to add captures for the preceding and following text:

str.replace(/(.*name="\w+)(\d+)(\w+".*)/, "$1!NEW_ID!$3")