3

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' with the following regexp:

 var regexp = /\d_(\d)_\d/;

But it returns me array containing

[1_2_3, 2]

So, when I try to use function 'replace' it actually replace '1_2_3' string instead of only '2'. I don't understand how to point to the second matched element in the replace function. Or maybe my regexp is wrong?

2
  • 1
    that's expected. the first entry in your matched results is always the entire string that caused the match. your actual captured values start at position [1]. Commented Jul 18, 2014 at 21:30
  • @MarcB ok, and how to tell "replace" function to work with value at position[1]? Commented Jul 18, 2014 at 21:32

1 Answer 1

5

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"
Sign up to request clarification or add additional context in comments.

2 Comments

Just a footnote: I thought "shouldn't that be \1?" Looking it up proved me wrong.
Thanks for providing information about $ sign. Very helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.