gpt4 book ai didi

Javascript正则表达式突出显示短语匹配

转载 作者:行者123 更新时间:2023-12-03 04:53:14 24 4
gpt4 key购买 nike

我编写了一个正则表达式,通过在短语周围添加跨度来突出显示文本中的匹配短语。文本可能包含 <b></b>文本和短语中的任何位置都将被匹配,忽略它。以下是我的代码:

var phraseArray = phrase.split(" ");
var phraseRegex = "";
if (phraseArray.length > 1) {
var regexSuffix = '+([/\\s]|<\/b>|<b>)+';
for (var i = 0; i < phraseArray.length; i++) {
phraseRegex += phraseArray[i] + regexSuffix;
if (i == phraseArray.length - 2) {
regexSuffix = "";
}
}
} else {
phraseRegex = phrase;
}
text = text.replace(new RegExp('(' + '([,\\s]|<\/b>|<b>)+' + phraseRegex + '([\\s/,.*]|<\/b>|<b>)+' + ')', 'gi'), '<span class="highlighted">&nbsp;$1&nbsp;</span>');

如果短语是 Airways Aviation文本是:

>    <b>Airways Aviation</b>. Airways Aviation  .Airways Aviation.  fra 
> Jet Airways. Jet Airways (India A range of talented people make it
> happen every day at Airways Aviation, .

以下是输出:

<span class="highlighting"> <b>Airways Aviation</b>.</span> Airways Aviation  .Airways Aviation.  fra 
> Jet Airways. Jet Airways (A range of talented people make it
> happen every day at<span class="highlighting"> Airways Aviation, .</span>

第二次出现的 Airways Aviation 并未突出显示。原因是什么?如何改进?

最佳答案

[EDIT based on your question edit]
[EDIT based on comment]

您必须使用g全局匹配标志。

  • 获取word待匹配
  • 创建一个新的正则表达式并添加 "(<b>)?"+word+"(</b>)?"//可能包含也可能不包含<b></b>在开始和结束时,g匹配全部
  • 将上面的正则表达式替换为 span
  • $& 添加匹配

var str="<b>Airways Aviation</b>. Airways<b> Aviation</b>  .Airways Aviation.  fra Jet Airways.  Jet Airways (India A range of talented people make ithappen every day at Airways Aviation, ."

function test(word){
word=word.split(" ").join("(<b>|</b>|\\s)*");
var re=new RegExp("(<b>)?"+word+"(</b>)?",'g');
console.log(str.replace(re,"<span class=\"highlighting\">$&</span>"));
}
test("Airways Aviation");

工作模式

function test(word){
word=word.split(" ").join("(<b>|</b>|\\s)*");
var re=new RegExp("(<b>)?"+word+"(</b>)?",'g');
var str=document.getElementById('div');
str.innerHTML=str.innerHTML.replace(re,"<span class=\"highlighting\">$&</span>");
}
span.highlighting{
background-color:#ccc;
color:#fff;
}
<body>
<div id="div"><b>Airways Aviation</b>. Airways<b> Aviation</b> .Airways Aviation. fra Jet Airways. Jet Airways (India A range of talented people make ithappen every day at <b>Airways</b> Aviation, .</div>
<button onclick="test('Airways Aviation');">Change</button>
</body>

关于Javascript正则表达式突出显示短语匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42558201/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com