最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to highlight text by using regex - Stack Overflow

programmeradmin1浏览0评论

I'm trying writing a script to help highlight when match with regex. Below is my example that what I do now.

var text = "SOMETHING ~WEIRDs~ AND Not WEIRD";
var regexp = /\b(WEIRD)\b/
var matches = text.match(regexp);

for (i = 0; i < matches.length; i++) {
  var replace_all = RegExp(matches[i] + "(?![^<]*>|[^<>]*<\/)", "ig");
  text = text.replace(eval(replace_all), "<span style='background-  color:yellow'>" + matches[i] + "</span>");
}
console.log(text);

I'm trying writing a script to help highlight when match with regex. Below is my example that what I do now.

var text = "SOMETHING ~WEIRDs~ AND Not WEIRD";
var regexp = /\b(WEIRD)\b/
var matches = text.match(regexp);

for (i = 0; i < matches.length; i++) {
  var replace_all = RegExp(matches[i] + "(?![^<]*>|[^<>]*<\/)", "ig");
  text = text.replace(eval(replace_all), "<span style='background-  color:yellow'>" + matches[i] + "</span>");
}
console.log(text);

The output of the code above is

SOMETHING ~<span style='background-  color:yellow'>WEIRD</span>s~ AND Not <span style='background-  color:yellow'>WEIRD</span>

The output I want is

SOMETHING ~WEIRDs~ AND Not <span style='background-  color:yellow'>WEIRD</span>

I would like to know is that anyway to write a regex contains regex and words provided? Or have any other method can solve this incorrect replace issue.

Share Improve this question edited Sep 7, 2017 at 11:22 Rory McCrossan 338k41 gold badges320 silver badges351 bronze badges asked Sep 7, 2017 at 11:14 DenoDeno 4346 silver badges17 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 7

Your outer regex is fine. The issue is with the inner replace_all regex in the loop , as it replaces all instances of the found string, no matter its position in the original string.

Instead use the original Regex with replace() using the matches within the replacement string, like this:

var text = "SOMETHING ~WEIRDs~ AND Not WEIRD";
var regexp = /\b(WEIRD)\b/
var text = text.replace(regexp, '<span style="background-color: yellow">$1</span>');
console.log(text);

Also, as a general rule, never, ever use eval(). There is always a better solution or alternative.

发布评论

评论列表(0)

  1. 暂无评论