使用javascript自动添加标记标记?

时间:2017-05-18 07:20:07

标签: javascript jquery html

如何自动为HTML内容添加标记标记?我想强调一下" milk",如下:

Word:牛奶

<mark>milk</mark>

示例:

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

就像那样:

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

1 个答案:

答案 0 :(得分:2)

使用正则表达式(正则表达式)查找单词“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>