Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
844 views
in Technique[技术] by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use $& and not $0 to refer to the entire match. I blame Perl.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...