javascript - Match a list of strings using RegEx -
i have function highlights amount of single word in string in angularjs. want change highlights of words input in array instead, i'm not sure how word regexp. here 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 plain string, 'cats', want change includes ['cats', 'registered', 'dog']
, on.
use join()
method join array elements pipe |
or operator in regex.
also, can use $&
matched string , use 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 , 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>')
Comments
Post a Comment