JS Regex, how to replace the captured groups only?

JS Regex, how to replace the captured groups only?

Ok the question is quite simple.
I’m looking for a string like this one :
name=”some_text_0_some_text”

I have HTML code before and after the string above.
Now i would like to replace the 0 by 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) by some other string ?
The result would be :
name=”some_text_!NEW_ID!_some_text”

Thanks for your help 🙂

Solutions/Answers:

Solution 1:

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

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

Solution 2:

A little improvement to Matthew’s answer could be a lookahead instead of the last capturing group:

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

Or you could split on the decimal and join with your new id like this:

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

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

Solution 3:

A simplier option is to just capture the digits 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

Related:  React Routing works in local machine but not Heroku