Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using $0 to refer to entire match in Javascript's String.replace

Tags:

I'm highlighting instances of a search string within a set of text. I want to preserve the case of the original text while replacing a case-insensitive match of the query. Here's what I started with:

text.replace(new RegExp('(' + query + ')', 'ig'), '<em>$1</em>');

In this case, I'd need to escape query to prevent parentheses from breaking the submatch, so I thought I'd try:

text.replace(new RegExp(query, 'ig'), '<em>$0</em>');

But $0 doesn't seem to be used - all matched strings are replaced with $0. I did find an alternative, however:

text.replace(new RegExp(query, 'ig'), function(match) { return '<em>' + match + '</em>'; });

I'm not a huge fan of how this looks, though. How would you recommend doing this type of string replacement?