This question already has answers here:
Find a string of text in an element and wrap some span tags round it
                                
                                    (6个答案)
                                
                        
                2年前关闭。
            
        

如何自动将标记标签添加到HTML内容?我想突出显示“牛奶”一词,如下所示:

词:牛奶

<mark>milk</mark>




范例:



<!DOCTYPE html>
<html>
<body>
<p>Do not forget to buy milk today.</p>
</body>
</html>





像那样 :



<!DOCTYPE html>
<html>
<body>
Do not forget to buy <mark>milk</mark> today.
</body>
</html>

最佳答案

使用正则表达式(正则表达式)查找单词“ milk”并将其替换,如下所示:



var key ='milk';
var regex = new RegExp(key,'g');
var text = document.getElementById('text').innerHTML;
console.log(text);
var newText =  text.replace(regex,'<mark>'+key+'</mark>' );
console.log(newText);
document.getElementById('text').innerHTML = newText;

<!DOCTYPE html>
<html>
<body>
<p id="text">
   Do not forget to buy milk today.
</p>
</body>
</html>





或者,您可以简单地写:




 document.getElementById('text').innerHTML = document.getElementById('text').innerHTML.replace(/(milk)/g,'<mark>$1</mark>' );

  <p id="text"> Do not forget to buy milk today. </p> 

09-25 15:45