简体   繁体   English

如何使用正则表达式突出显示字符串中的多个关键字/词?

[英]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.

相关问题 如何使用 react-highlight-words 突出显示具有不同 colors 的多个关键字 - how to use react-highlight-words to highlight multiple keywords with different colors 一个正则表达式来突出显示文本中的单词 - A regex to highlight words in text 如何从不同输入字符串的javascript,jquery,regex的响应中突出显示动态单词 - How to highlight dynamic words from response for different input string javascript, jquery, regex 正则表达式模式突出显示双引号内的序列字符串单词 - regex pattern highlight n sequence string words inside double quotes 如何将字符串与单词数组进行比较并突出显示匹配字符串中的单词? - How to compare string with array of words and highlight words in string that match? 如何通过单击按钮在 JavaScript 中突出显示多个单词 - How to highlight multiple words in JavaScript with button click 如何使用“突出显示文本区域”插件突出显示多个单词 - How to highlight multiple words with the Highlight Text Area plugin 如何匹配正则表达式中的多个单词 - How to match multiple words in regex 正则表达式 - 匹配字符串中的多个无序单词 - Regex - match multiple unordered words in a string 正则表达式匹配字符串中多个单词的开头 - Regex match for beginning of multiple words in string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM