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"
A solution is to add captures for the preceding and following text:
str.replace(/(.*name="\w+)(\d+)(\w+".*)/, "$1!NEW_ID!$3")
Now that Javascript has lookbehind (as of ES2018), on newer environments, you can avoid groups entirely in situations like these. Rather, lookbehind for what comes before the group you were capturing, and lookahead for what comes after, and replace with just !NEW_ID!
:
const str = 'name="some_text_0_some_text"'; console.log( str.replace(/(?<=name="\w+)\d+(?=\w+")/, '!NEW_ID!') );
With this method, the full match is only the part that needs to be replaced.
(?<=name="\w+) - Lookbehind for name=", followed by word characters (luckily, lookbehinds do not have to be fixed width in Javascript!)
\d+ - Match one or more digits - the only part of the pattern not in a lookaround, the only part of the string that will be in the resulting match
(?=\w+") - Lookahead for word characters followed by " `
Keep in mind that lookbehind is pretty new. It works in modern versions of V8 (including Chrome, Opera, and Node), but not in most other environments, at least not yet. So while you can reliably use lookbehind in Node and in your own browser (if it runs on a modern version of V8), it's not yet sufficiently supported by random clients (like on a public website).
\d+
, right?
match => match * 2
. The digits are still the whole match, so there's no need for groups
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
With two capturing groups would have been also possible; I would have also included two dashes, as additional left and right boundaries, before and after the digits, and the modified expression would have looked like:
(.*name=".+_)\d+(_[^"]+".*)
const regex = /(.*name=".+_)\d+(_[^"]+".*)/g; const str = `some_data_before name="some_text_0_some_text" and then some_data after`; const subst = `$1!NEW_ID!$2`; const result = str.replace(regex, subst); console.log(result);
If you wish to explore/simplify/modify the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.
RegEx Circuit
jex.im visualizes regular expressions:
https://i.stack.imgur.com/xYswa.png
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
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
"some_text_0_some_text".replace(/(?=\w+)\d+(?=\w+)/, '!NEW_ID!')
Result is
some_text_!NEW_ID!_some_text
const regExp = /(?=\w+)\d+(?=\w+)/; const newID = '!NEW_ID!'; const str = 'some_text_0_some_text'; const result = str.replace(regExp, newID); console.log(result);
x(?=y)
in JS RegExp
Matches "x" only if "x" is followed by "y". For example, /Jack(?=Sprat)/
matches "Jack" only if it is followed by "Sprat". /Jack(?=Sprat|Frost)/
matches "Jack" only if it is followed by "Sprat" or "Frost". However, neither "Sprat" nor "Frost" is part of the match results.
Success story sharing
$
, so the first word(\w+)
is in a group, and becomes$1
, the middle part(\d+)
is the second group, (but gets ignored in the replace), and the third group is$3
. So when you give the replace string of"$1!new_ID!$3"
, the $1 and $3 are replaced automagically with the first group and third group, allowing the 2nd group to be replaced with the new string, maintaining the text surrounding it.