[英]How to highlight multiple keywords/words in a string with Regex?
I have the following case that I am trying to solve.我有以下案例要解决。
Javascript Method that highlights keywords in a phrase. Javascript 在短语中突出显示关键字的方法。
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 https://regex101.com/r/V8o6gN/5
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. 如果我没有弄错的话,你基本上想找到你的
keywords
变量中的每个单词,并在你的字符串中匹配它们,这样你就可以将它们包裹在一个范围内。
You'll want to first turn your keywords into a RegExp, then do a global match. 您首先要将关键字转换为RegExp,然后进行全局匹配。 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. 然后你只想进行全局搜索(
g
标志),以便匹配所有这些。
With the global flag, there is no need to do a loop. 使用全局标志,不需要循环。 You can get them all in one shot.
你可以一次性完成它们。
Based on @samanime answer.基于@samanime 的回答。 I remove duplicates, trim spaces and highlight longer words first.
我首先删除重复项、修剪空格并突出显示较长的单词。
The only problem is a matches that span an element boundary.唯一的问题是跨越元素边界的匹配。 For example ["elem", "lemen"] in "The element"
例如“The element”中的 ["elem", "lemen"]
const tokens = [...new Set(state.highlight.split(' '))]
.map(s => s.trim())
.filter(s => s.length)
.sort((a,b) => b.length - a.length);
const pattern = new RegExp(`(${tokens.join('|')})`, 'ig');
const highlighted = this.state.value.replace(pattern, match => `<b>${match}</b>`);
console.log(highlighted);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.