我有一个很长的段落,需要突出显示数组中包含的关键字。我能够循环遍历数组并突出显示段落中每个单词的第一次出现。但是,我无法突出显示后续发生的情况。
这与提出的问题非常接近here 。
在下面的示例中,我试图查找并突出显示所有出现的“dog”和“field”。
由于 "g"
标志,这适用于查找每个单词的所有出现位置。
var re = new RegExp(arr.join("|"), "g")
console.log('keywords are ' + re);
console.log('The matches are ' + str.match(re));
但我不确定 replace
中是否以及何处应该有 "g"
标志。
<p id="x"></p>
<script>
var arr = ("The dog ran through the field. The dog ate."); //paragraph from which to search
document.getElementById("x").innerHTML = arr;
var words = ["dog", "field"]; //array of keywords
var str = document.getElementById("x").innerHTML;
var re = new RegExp(words.join("|"), "gi"); // create a a | b | c regex
console.log(words);
console.log(re, str.match(re));
console.log('keywords are ' + re);
console.log('The matches are ' + str.match(re));
str.match(re).forEach(function(match, i) { // loop over the matches
str = str.replace(match, function replace(match) { // wrap the found strings
return '<em>' + match + '</em>';
});
});
document.getElementById("x").innerHTML = str
</script>
em { background-color:yellow }
我尝试过使用 str.replace(/match/g, function(match, i)
。这不会出错,但会删除所有突出显示。
最佳答案
可能你不需要match(re).forEach
,只需单独使用replace(re)
var arr = ("The dog ran through the field. The dog ate."); //paragraph from which to search
document.getElementById("x").innerHTML = arr;
var words = ["dog", "field"]; //array of keywords
var str = document.getElementById("x").innerHTML;
var re = new RegExp(words.join("|"), "gi"); // create a a | b | c regex
str = str.replace(re, function replace(match) { // wrap the found strings
return '<em>' + match + '</em>';
});
document.getElementById("x").innerHTML = str
<p id="x"></p>
关于javascript - 突出显示关键字数组中段落中所有出现的特定单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57098013/