I'm highlighting instances of a search string within a set of text. I want to preserve the case of the original text whi开发者_JAVA技巧le 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?
Use $&
and not $0
to refer to the entire match. I blame Perl.
use $$0 instead of $0
str.replace(/\$/,'$$')
精彩评论