我编写了一个正则表达式,通过在短语周围添加一个范围来突出显示文本中匹配的短语。文本可能在文本中的任何位置包含<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"> $1 </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>
第二次出现的航空航空没有突出显示。是什么原因以及如何加强?
答案 0 :(得分:1)
[编辑基于您的问题编辑]
[编辑基于评论]
您必须使用g
标志进行全局匹配。
word
"(<b>)?"+word+"(</b>)?"
//在开始和结束时可能包含<b>
和</b>
,但g
匹配所有
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");
&#13;
工作模式
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>");
}
&#13;
span.highlighting{
background-color:#ccc;
color:#fff;
}
&#13;
<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>
&#13;