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

时间:2018-11-23 02:42:31

标签: javascript jquery arrays contains

我想检查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>

有什么想法吗?

2 个答案:

答案 0 :(得分:3)

一个选择是将join的水果转换成全局正则表达式(它将匹配任何水果子字符串),然后将.replace的每个html() div的.mystr {带有<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>

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

答案 1 :(得分:1)

这可能不是最有效的解决方案,因为它正在为每个字符串迭代所有水果,但是如果您的水果和.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)  
});

这是一个可以工作的codepen https://codepen.io/ederdiaz/pen/QJmmvg