Regex Guru

Tuesday, 8 June 2010

Replacement Text Syntax for JavaScript’s String.replace()

Filed under: Regex Libraries — Jan Goyvaerts @ 17:16

A RegexBuddy user told me that he couldn’t easily find a detailed explanation of the replacement text syntax supported by the String.replace() function in JavaScript. I had to admin that my own web page about JavaScript’s regular expression support was also lacking. I’ve now added a new Replacement Syntax section that has all the details. I’ll summarize it here:

  • $1: Text matched by the first capturing group or the literal text $1 if the regex has no capturing groups.
  • $99: Text matched by the 99th capturing group if the regex has 99 or more groups. Text matched by the 9th capturing group followed by a literal 9 if the regex has 9 or more but less than 99 groups. The literal text $99 if the regex has fewer than 9 groups.
  • $+: Text matched by the highest-numbered capturing group. Replaced with nothing if the highest-numbered group didn’t participate in the match.
  • $&: Text matched by the entire regex. You cannot use $0 for this.
  • $` (backtick): Text to the left of the regex match.
  • $' (single quote): Text to the right of the regex match.
  • $_: The entire subject string.

2 Comments

  1. This list is missing $$, which inserts a single dollar sign.

    Also note that $+ and $_ are not part of the JavaScript specification and should not be used. Anywhere they are supported, they are browser-specific extensions. Specifically, $_ works in IE only, and $+ works in IE and Firefox only. Neither work in the current versions of Chrome, Safari, or Opera.

    Comment by Steven Levithan — Thursday, 10 June 2010 @ 18:23

  2. I’ve updated the JavaScript and flavor comparison pages to clarify that these are browser-specific extensions. (Which I should have known because we got it right in chapter 2 of our book.)

    Comment by Jan Goyvaerts — Friday, 11 June 2010 @ 16:25

Sorry, the comment form is closed at this time.