JS Regex, how to replace only captured groups?

Well, the question is pretty simple. I am looking for a line like this:

name="some_text_0_some_text" 

I have HTML code before and after the line above.

Now I would like to replace 0 with something like !NEW_ID!

So, I made a simple regex:

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

But I do not see how to replace an exclusively captured block.

Is there a way to replace the captured result, for example ($ 1), with some other line?

The result will be:

 name="some_text_!NEW_ID!_some_text" 

Thanks for your help :)

+143
javascript regex
Oct. 17 '10 at 19:38
source share
3 answers

The solution is to add captures for the previous and next text:

 str.replace(/(.*value="\w+)(\d+)(\w+".*)/, "$1!NEW_ID!$3") 
+282
Oct 17 '10 at 19:45
source share

A slight improvement in Matthew's answer may be an anticipation instead of the last capture group:

 .replace(/(\w+)(\d+)(?=\w+)/, "$1!NEW_ID!"); 

Or you can split the decimal and join with your new identifier as follows:

 .split(/\d+/).join("!NEW_ID!"); 

Example / test here: https://codepen.io/jogai/full/oyNXBX

+1
May 29 '18 at 9:14
source share

A simpler option is to just grab the numbers and replace them.

 const name = 'preceding_text_0_following_text'; const matcher = /(\d+)/; // Replace with whatever you would like const newName = name.replace(matcher, 'NEW_STUFF'); console.log("Full replace", newName); // Perform work on the match and replace using a function // In this case increment it using an arrow function const incrementedName = name.replace(matcher, (match) => ++match); console.log("Increment", incrementedName); 

Resources

0
Jun 25 '19 at 6:52
source share



All Articles