使用正则表达式突出显示一串字符串

时间:2018-04-23 16:00:24

标签: javascript regex algorithm

如何突出显示一串字符串? 我的问题在这里我要强调一个集团中的所有单词a reference 喜欢这个图像

enter image description here

当我在""内有单词时,双引号var wordsToHighlight =' "word1, word2" '表示在整篇文章中突出显示word1 word2

我的问题需要突出显示整篇文章中双引号内的文字

阐释:

*它是一个截断并且效果很好

?突出显示单词+ n个字符



var row = {
  "Abstract": "a reference I have a reference server for reference and just a server here server test." 
};

var wordsToHighlight = `reference  "a reference"  reference jus? fo* `;
var result = row["Abstract"];

  
var words=wordsToHighlight ;
var resultAbstract = row["Abstract"];
var wordsTH2=[], m;
var rx = /["“']([^"”']+)["”']|\S+/g;
while (m=rx.exec(words)) {
  if (m[1]) {
     var arr = m[1].trim().split(/\s*,\s*/);
     for (var i=0; i<arr.length;i++) {
        wordsTH2.push(arr[i]);
     }
  } else {
    wordsTH2.push(m[0]);
  }
}
//sort wordsTH2 by length in a descending order
wordsTH2.sort(function(a, b){
  return b.length - a.length;
});
wordsTH2.forEach(function (word) {
word = word.replace(/\*/g, '\\S*').replace(/\?/g, '.');
//<span style="background-color:yellow;">.*?</span>|  it will match terms that are already highlighted and won't touch them since if it matches, Group 1 and 2 are undefined and if Group 1 and 2 match, a term ($2) will get wrapped with the new span

resultAbstract = resultAbstract.replace(new RegExp('<span style="background-color:yellow;">.*?</span>|(\\s|^)(' + word + ')(?=\\s|$)', "gi"),function ($0, $1, $2) { return $1 ? $1 + '<span style="background-color:yellow;">' + $2 + '</span>' : $0; });
});
document.querySelector("#result").innerHTML = resultAbstract;
&#13;
<div id="result"></div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

问题在于(\\s|^)以及后续检查第1组。当^(字符串的开头)匹配时,$1变量仍然评估为 false ,并且替换整个值。

检查第2组是否匹配似乎更有意义,将return $1 ?替换为return $2 ?,因为第2组不能为空或null / undefined:

var row = {
  "Abstract": "a reference I have a reference server for reference and just a server here server test." 
};

var wordsToHighlight = `reference  "a reference"  reference jus? fo* `;
var result = row["Abstract"];

  
var words=wordsToHighlight ;
var resultAbstract = row["Abstract"];
var wordsTH2=[], m;
var rx = /["“']([^"”']+)["”']|\S+/g;
while (m=rx.exec(words)) {
  if (m[1]) {
     var arr = m[1].trim().split(/\s*,\s*/);
     for (var i=0; i<arr.length;i++) {
        wordsTH2.push(arr[i]);
     }
  } else {
    wordsTH2.push(m[0]);
  }
}
//sort wordsTH2 by length in a descending order
wordsTH2.sort(function(a, b){
  return b.length - a.length;
});
wordsTH2.forEach(function (word) {
word = word.replace(/\*/g, '\\S*').replace(/\?/g, '.');
resultAbstract = resultAbstract.replace(new RegExp('<span style="background-color:yellow;">.*?</span>|(\\s|^)(' + word + ')(?=\\s|$)', "gi"),function ($0, $1, $2) { return $2 ? $1 + '<span style="background-color:yellow;">' + $2 + '</span>' : $0; });
});
document.querySelector("#result").innerHTML = resultAbstract;
<div id="result"></div>