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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…