Javascript RegEx突出显示短语匹配

时间:2017-03-02 14:33:22

标签: javascript regex

我编写了一个正则表达式,通过在短语周围添加一个范围来突出显示文本中匹配的短语。文本可能在文本中的任何位置包含<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>

第二次出现的航空航空没有突出显示。是什么原因以及如何加强?

1 个答案:

答案 0 :(得分:1)

  

[编辑基于您的问题编辑]
  [编辑基于评论]

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

  • 获取匹配的word
  • 通过添加创建一个新的RegExp  "(<b>)?"+word+"(</b>)?" //在开始和结束时可能包含<b></b>,但g匹配所有
  • 用span
  • 替换上面的正则表达式
  • $&安培;添加比赛

&#13;
&#13;
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;
&#13;
&#13;

工作模式

&#13;
&#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;
&#13;
&#13;