正则表达式模式突出显示双引号内的序列字符串单词

时间:2018-04-09 17:33:04

标签: javascript regex

我的脚本突出显示文本字符串中的特定单词我唯一的问题是,当我想要突出显示三个序列单词时,它只突出显示第一个单词,然后第二个单词仍然没有突出显示,然后第三个突出显示

*它的截断并且效果很好

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

这是一个突出显示n个序列词的例子。 我的问题在这里我要强调""内的词语 当我有双引号时突出显示引号内的单词。

"参考是"需要突出显示不分开的单词

exp:引用好是test1 test2(此处仅突出显示reference is



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

//here i need to highlight "reference is" to serve test* (n sequnence words)

var wordsToHighlight = '"reference is" to ser?? test*';
var result = row["Abstract"];

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

1 个答案:

答案 0 :(得分:1)

您需要将原始wordsToHighlight字符串与

分开
.split(/"([^"]+)"|\s+/).filter(Boolean)

它将使用双引号子串分割字符串,同时将双引号之间的子字符串推送到结果数组中(String#split始终将捕获的子字符串推送到结果数组中),并使用1 +空格和{{1}将删除在拆分操作期间可能产生的空项目。

请参阅regex demo

JS演示:

&#13;
&#13;
.filter(Boolean)
&#13;
var row = {
  "Abstract": "This reference is to serve test as a useful reference for testing whether the styling of reference works or not. Adtest all occurrences of 'reference' should be given a color of red tests" 
};

//here i need to highlight "reference is" to serve test* (n sequnence words)

var wordsToHighlight = '"reference is" to ser?? test*';
var result = row["Abstract"];

wordsToHighlight.split(/"([^"]+)"|\s+/).filter(Boolean).forEach(function (word) {
  word = word.replace(/\*/g, '\\S*').replace(/\?/g, '.').replace(/\"/g, '.');
  result = result.replace(new RegExp('(\\s|^)(' + word + ')(?=\\s|$)', "gi"),'$1<span style="background-color:yellow;">$2</span>');
});
document.querySelector("#result").innerHTML = result;
&#13;
&#13;
&#13;