繁体   English   中英

JavaScript上的正则表达式如何在正向向后和正向向前添加全词搜索和不区分大小写

[英]Regular expression on JavaScript how to add whole word search and case insensitive in positive look behind and positive look ahead

我需要对一个关于搜索整个单词并在一个段落中更改其 styles 的项目进行一些调整。 网上有类似的问题,但我发现在这种情况下答案仍然无效。

//text contains words
const text=" there are some keywords that need to be found and changed. key is a different word."
//words need to be whole search
const words=["keywords","key","need"] 
//split the text by words, after the split if the element match words then change style  
const ChangeStyle=(text, words)=>{
  return ({text.split(new RegExp(`(?<=${words.join("|")})|(?=${words.join("|")})`))
.map((element)=>{ return words.include(element)?(<span style={{color:red}}>{element}</span>):
{element}
})})
}

问题是在使用单词数组中的所有单词进行拆分工作之后。 甚至文本中的“关键字”也会被“关键字”拆分,分成“关键字”和“单词”。这样“关键字”本身就永远找不到并改变样式。 在这种情况下,只会在文本中找到“key”和“need”并更改样式。我尝试对 words 数组进行排序,结果是一样的。

在正则表达式“(\bword[\s.])”中,我认为可以完成整个单词搜索工作(找到以单词边界开头的“单词”,以点或空格结尾)。

在这种情况下,如果我想保留拆分逻辑,如何将 "\bword[\s.]" 组合到上面的 regExp 中,以便它会进行整个单词拆分和不区分大小写?

如果您使用replace而不是“拆分”,它将在下一个单词之后替换一个单词。 工作示例:

 const text = " there are some keywords that need to be found and changed. key is a different word."; const words = ["keywords","key","need"]; const ChangeStyle = (text, words) => { let re = new RegExp('\\b(' + words.join('|') + ')\\b', 'g'); return text.replace(re, function(m) { return '<span style="{{color:red}}">' + m + '</span>'; }); } console.log(ChangeStyle(text, words));

Output:

there are some <span style="{{color:red}}">keywords</span> that <span style="{{color:red}}">need</span> to be found and changed. <span style="{{color:red}}">key</span> is a different word.

正则表达式的解释:

  • '\\b(' - 单词边界(注意字符串定义中的转义反斜杠)和组的开始
  • words.join('|') - 你的话或组合
  • ')\\b' - 组结束和单词边界
  • 'g' - 替换所有出现的全局标志

暂无
暂无

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

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