Issue
I have the following case that I am trying to solve.
Javascript Method that highlights keywords in a phrase.
vm.highlightKeywords = (phrase, keywords) => {
keywords = keywords.split(' ');
let highlightedFrase = phrase;
angular.forEach(keywords, keyword => {
highlightedFrase = highlightedFrase.replace(new RegExp(keyword + "(?![^<])*?>)(<\/[a-z]*>)", "gi"), function(match) {
return '<span class="highlighted-search-text">' + match + '</span>';
});
});
return $sce.trustAsHtml(highlightedFrase)
}
How can I write a regular expression that will match this case so that I can replace the substrings
keyowrds = 'temperature high'
phrase = 'The temperature is <span class="highlight">hig</span>h'
ReGex Case
https://regex101.com/r/V8o6gN/5
Solution
If I'm not mistaken, your basically wanting to find each word that is a word in your keywords
variable and match them in your string so you can wrap them in a span.
You'll want to first turn your keywords into a RegExp, then do a global match. Something like this:
const keywordsString = "cake pie cookies";
const keywords = keywordsString.split(/\s/);
// equivalent to: /(cake|pie|cookies)/g
const pattern = new RegExp(`(${keywords.join('|')})`, 'g');
const phrase = "I like cake, pie and cookies";
const result = phrase.replace(pattern, match => `<span>${match}</span>`);
console.log(result);
Basically, you want a pattern where your keywords are pipe (|
) separated and wrapped in parentheses (()
). Then you just want to do a global search (g
flag) so you match all of them.
With the global flag, there is no need to do a loop. You can get them all in one shot.
Answered By - samanime
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.