我需要根据一些图案给一些单词上色
例如,我想为所有开始或结束或包含模式 *test*
- 示例:测试、测试、测试、tesdaf
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 a truncation for examaple test*
var wordsToHighlight = 'reference test*';
var result = row["Abstract"];
wordsToHighlight.split(" ").forEach(function (word) {
result = result.replace(new RegExp(word, "g"),'<span style="color: red;">'+word+'</span>');
});
document.querySelector("#result").innerHTML = result;
<div id="result">
<!-- begin snippet: js hide: false console: true babel: false -->
</div>
通常“testing”“Adtest”等词都会被高亮显示。
我需要帮助。
寻找您的建议
最佳答案
用更通用的方式替换您的 *
以匹配:
注意:代码应该注意更具体的正则表达式字符,否则它可能会中断,例如带有圆括号的单词会捕获组等。通常它们可以用 转义\
(就像我在正则表达式 /\*/
中转义 *
的方式一样)。在字符串中,您需要加倍 \
,例如 '\\S*'
编辑:在开头添加正则表达式 (?:\\s|^)
和 (?:\\s|$)
在单词的末尾,因此 test*
不会突出显示 Adtest
的最后部分,而是突出显示整个单词(如果它对应的话)。 (它验证单词周围是否有空格或字符串的开头/结尾)
编辑 2:根据最后的评论和正则表达式无法突出显示连续单词的事实:这是因为空格被捕获并因此转移到跨度中,因此无法检测到空格对于以下单词。通过单独捕获空间并在跨度之前和之后重新插入它们进行了更新。也为首都添加了 i
标志。
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 a truncation for examaple test*
var wordsToHighlight = 'reference test*';
var result = row["Abstract"];
wordsToHighlight.split(" ").forEach(function (word) {
word = word.replace(/\*/g, '\\S*');
result = result.replace(new RegExp('(\\s|^)(' + word + ')(\\s|$)', "gi"),'$1<span style="color: red;">$2</span>$3');
});
document.querySelector("#result").innerHTML = result;
wordsToHighlight = 'This is reference *test*';
result = row["Abstract"];
wordsToHighlight.split(" ").forEach(function (word) {
word = word.replace(/\*/g, '\\S*');
result = result.replace(new RegExp('(\\s|^)(' + word + ')(\\s|$)', "gi"),'$1<span style="color: red;">$2</span>$3');
});
document.querySelector("#result2").innerHTML = result;
<div id="result"></div>
<br/>
<div id="result2"></div>
关于javascript - 如何用 Javascript 进行替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48810252/