12

How do you use the matched variables in the pattern in the replacement string?

var regexp = new RegExp('needle', 'ig');
str.replace(regexp, '<span class="marked">//1</span>')
3
  • 1
    I think you should have a read of this codinghorror.com/blog/2009/11/parsing-html-the-cthulhu-way.html Commented Aug 9, 2011 at 8:46
  • 4
    @Peter Kelly: I'm not sure this is valid - his example does not reference parsing HTML, but instead deals with adding HTML tags around a string. Which is a perfectly valid use for a Regex. Commented Aug 9, 2011 at 8:47
  • Where did you see that you could use //1? Read the documentation on the replace string more closely, especially the part about the special $ variables. Commented Oct 28, 2016 at 14:03

2 Answers 2

28

try

var regexp = new RegExp(something, 'ig');
str.replace(regexp, '<span class="marked">$&</span>')

References:

Sign up to request clarification or add additional context in comments.

3 Comments

it works.. but why $& ? what if you got some groups in the pattern.. $1 etc doesnt seem to work
Interesting. I actually didn't know about the $&, $' and $` replacements.
@claekk: $& represent the matched string, $n represent the nth group matched. If you don't use group matching should be preferable ($1 should work too, though). See the reference I added
7

The correct way to use backreferences in JavaScript is via $1...$9.

To make your example work:

var regexp = new RegExp(something, 'ig');
var result = str.replace(regexp, '<span class="marked">$1</span>');

More information is available here: http://www.regular-expressions.info/javascript.html#replace

1 Comment

To use the numeric backreferences, you'll need to wrap your regex in parentheses: /(needle)/. Otherwise, use $& that Eineki shows.

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.