javascript - 突出显示关键字数组中段落中所有出现的特定单词

标签 javascript highlight

我有一个很长的段落,需要突出显示数组中包含的关键字。我能够循环遍历数组并突出显示段落中每个单词的第一次出现。但是,我无法突出显示后续发生的情况。

这与提出的问题非常接近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/

相关文章:

javascript - 如何删除javascript中的表单自动填充

javascript - 谷歌应用可视化可以吗?具有缩放选项的时间轴

jupyter - 在 Jupyterlab 3 中更改鼠标选择颜色

graph - gnuplot:标记/突出显示区域(折线图的一部分)

c# - TextHighlighter RichTextBlock UWP

javascript - MongoClient的findOne()永远不会在Electron上解析,即使填充了集合

javascript - 将带有换行符的字符串格式化为段落

Java Applet 文件权限错误

javascript - React - 突出显示给定 Xpath 的angerlySetHTML 内的文本

powershell - PowerShell 中的着色数组筛选器