我的段落很长,需要突出显示数组中包含的关键字。我能够遍历数组并突出显示段落中每个单词的第一个出现。但是,我无法突出显示随后发生的情况。
这非常接近here提出的问题。
在下面的示例中,我试图查找并突出显示所有出现的“狗”和“田地”。
由于"g"
标志,这可用于查找每个单词的所有出现。
var re = new RegExp(arr.join("|"), "g")
console.log('keywords are ' + re);
console.log('The matches are ' + str.match(re));
但是我不确定"g"
中是否应该有replace
标志。
<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)
。这不会出错,但是会删除所有突出显示。
答案 0 :(得分:1)
可能您不需要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>
答案 1 :(得分:0)
要获得预期结果,请使用以下选项,将 RegExp 构造函数用于全局匹配,并将其用于替换变量
var glob = new RegExp(match, "g");
str = str.replace(glob, function replace(match) { // wrap the found strings
return '<em>' + match + '</em>';
});
示例工作代码
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
var glob = new RegExp(match, "g");
str = str.replace(glob, function replace(match) { // wrap the found strings
return '<em>' + match + '</em>';
});
});
document.getElementById("x").innerHTML = str
em { background-color:yellow }
<p id="x"></p>
<script>
</script>