简体   繁体   English

使用RegEx匹配字符串列表

[英]Match a list of strings using RegEx

I have a function that highlights any amount of a single word in a string in AngularJS. 我有一个突出显示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. 我想更改此设置,以使其突出显示我在数组中输入的所有单词,但是我不确定如何为RegExp编写单词。 Here is the current RegExp: 这是当前的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. 当前的“ needle”变量只是一个普通字符串,例如“ cats”,但我想更改它,使其包含['cats', 'registered', 'dog']等。

Use the join() method to join the array elements by the pipe | 使用join()方法通过管道连接数组元素| which is OR operator in regex. 这是正则表达式中的OR运算符。

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 . 要匹配精确的单词,请使用单词边界\\b

str.replace(new RegExp('\\b(' + arr.join('|') + ')\\b', 'gi'), '<span class="highlightWord">$1</span>')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM