【发布时间】:2018-04-23 16:00:23
【问题描述】:
如何突出显示一个字符串?
我的问题在这里我想在一个集团中突出显示所有单词a reference
喜欢这张图片
当我在"" 内有单词时,双引号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;
<div id="result"></div>
【问题讨论】:
标签: javascript regex algorithm