Search code examples
javascriptjqueryregexpcregrep

How to highlight text by using regex


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.


Solution

  • 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.