如果element包含任何这些单词,则将该单词包含在span中

Jer*_*rpl 1 javascript jquery contains keyword

如果通过在span类中包含这些单词而在标题中找到它们,我想强调某些单词.有没有办法编写一个单词列表来检查,然后使用相同的命令用span类包装任何这些单词?

例如:

<h1>This title contains the word Balloon</h1>
<h1>This title contains the word Oranges</h1>
<h1>This title doesn't contain either of those terms</h1>
Run Code Online (Sandbox Code Playgroud)

要检查这三个元素中的每个元素(但是会有20个左右)用于Balloon或Oranges,然后用span颜色包裹这些单词.

我可以用:

$('h1').html($('h1').html().replace(/(balloon)/g,'<span class="red">balloon</span>'));
Run Code Online (Sandbox Code Playgroud)

但是我必须为每个单词写出那个查询,而如果可能的话,我想要一些更简单的东西.

ade*_*neo 5

您可以保留一个单词数组,然后迭代并替换每个标题中的单词

var words = [
    "balloon",
    "either"
];

$('h1').html(function(_,html) {
    var reg = new RegExp('('+words.join('|')+')','gi');
    return html.replace(reg, '<span class="red">$1</span>', html)
});
Run Code Online (Sandbox Code Playgroud)
.red {color : red}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h1>This title contains the word Balloon</h1>
<h1>This title contains the word Oranges</h1>
<h1>This title doesn't contain either of those terms</h1>
Run Code Online (Sandbox Code Playgroud)