检查 div 内容是否包含数组中的单词并替换它

Check if a div content contain a word from an array and replace it

我想检查 div 的内容是否包含数组中的单词并向该单词添加一些标签,例如 <b></b>

这是我的代码:

var fruits = ["banana", "peach", "grappe", "lemon", "apple"];
          $( ".mystr" ).each(function() {
            mystr =   $( this ).html();
           if (fruits.some(function(v) { return mystr.indexOf(v) >= 0; })) {
// get the fruit and replace it with <b>thefruit</b>
//and print it in a div   
//"<div class='mynewstr'></div>"
           }      


            });
<div class='container'>

    <div class='mystr'>I love apple </div>
    <div class='mystr'>I don't  like banana</div>
    <div class='mystr'>I don't  like peach</div>
    <div class='mystr'>I  like both grappe and lemon</div>


    


    </div>

例如

<div class='mystr'>I love apple </div>

必须变成

<div class='mynewstr'>I love <b>apple</b></div>

有什么想法吗?

一个选择是 join 将水果放入全局正则表达式(它将匹配任何水果子字符串),然后 .replace 每个 [=15= 的 html() ] div 周围有<b></b>个水果词:

const fruits = ["banana", "peach", "grappe", "lemon", "apple"];
const pattern = new RegExp(fruits.join('|'), 'g');
$(".mystr").each(function() {
  $(this).html(
    $(this).html().replace(pattern, '<b>$&</b>')
  );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='container'>

  <div class='mystr'>I love apple </div>
  <div class='mystr'>I don't like banana</div>
  <div class='mystr'>I don't like peach</div>
  <div class='mystr'>I like both grappe and lemon</div>
</div>

(请注意,替换字符串中的 $& 会替换为 整个匹配的子字符串

这可能不是最高效的解决方案,因为它会为每个字符串迭代所有水果,但如果您的水果和 .mystr 集不是特别大,那应该不是问题:

var fruits = ["banana", "peach", "grappe", "lemon", "apple"];
$( ".mystr" ).each(function() {
  mystr = $( this ).html();
  fruits.forEach(f => {
    mystr = mystr.replace(f,`<b>${f}</b>`, 'g')
  }) 
  $( this ).html(mystr)  
});

这是一个可以正常工作的代码笔 https://codepen.io/ederdiaz/pen/QJmmvg