Skip to content Skip to sidebar Skip to footer

Js Replace Digits With Regular Expressions

I have an identifiers of the elements, which look like this: form_book_1_2_3 What I want is to replace second digit in this identifier with other value. I used function 'match' wi

Solution 1:

The replace function will replace the entire matched string, not just a specific capture group. The easy solution is to capture the parts of the string that you don't want to modify and use them as references in the replacement pattern, for example:

"form_book_1_2_3".replace(/(\d)_\d_(\d)/, "$1_X_$2"); //"form_book_1_X_3"

For reference, the full syntax for replacement patterns is (from MDN):

  • $$ — Inserts a "$".
  • $& — Inserts the matched substring.
  • $` — Inserts the portion of the string that precedes the matched substring.
  • $' — Inserts the portion of the string that follows the matched substring.
  • $n or $nn — Where n or nn are decimal digits, inserts the nth parenthesized submatch string, provided the first argument was a RegExp object.

Alternatively, you could use a function to accomplish the same goal, like this:

var replacer = function(match, a, b) { return a + "_X_" + b; };
"form_book_1_2_3".replace(/(\d)_\d_(\d)/, replacer); // "form_book_1_X_3"

Post a Comment for "Js Replace Digits With Regular Expressions"