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 :

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 :

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 :

Thanks for your help 🙂


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:


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);