Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match a list of strings using RegEx

I have a function that highlights any amount of a single word in a string in AngularJS. I want to change this so it highlights any of the words I input in an array instead, but I'm not sure how to word the RegExp. Here is the current RegExp:

$scope.highlight = function(haystack) {
    return $sce.trustAsHtml(haystack.replace(new RegExp(needle, "gi"), function(match) {
        return '<span class="highlightWord">' + match + '</span>';
    }));
};

The current "needle" variable is just a plain string, like 'cats', but I want to change that so it includes ['cats', 'registered', 'dog'] and so on.

like image 654
Organiccat Avatar asked Jan 29 '26 15:01

Organiccat


1 Answers

Use the join() method to join the array elements by the pipe | which is OR operator in regex.

Also, you can use $& to get the matched string and use it in replace string.

$scope.highlight = function (haystack) {
    return $sce.trustAsHtml(haystack.replace(new RegExp(needle.join('|'), "gi"), '<span class="highlightWord">$&</span>'));
};

var arr = ['cat', 'dog', 'elephant'];
var str = 'Cat fears dog and dog fears elephant';

document.body.innerHTML = str.replace(new RegExp(arr.join('|'), 'gi'), '<span class="highlightWord">$&</span>');
.highlightWord {
  background: yellow;
}

To match exact words, use word boundary \b.

str.replace(new RegExp('\\b(' + arr.join('|') + ')\\b', 'gi'), '<span class="highlightWord">$1</span>')
like image 138
Tushar Avatar answered Jan 31 '26 03:01

Tushar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!