向 html 字符串添加粗体标记

Adding bold tags to a string of html

本文关键字:添加 html 字符串      更新时间:2023-09-26

我在javascript/jquery中有一个html字符串。

var str = '<div id="cheese" class="appleSauce"> I like <a href="apple.com"> apple </a> and cheese</div>';

我想使字符串"苹果"加粗。 所以我这样做:

str = str.replace('apple','<b>apple</b>');

但这会破坏字符串的 HTML 部分。 我得到:

<div id="cheese" class="<b>apple</b>Sauce"> I like <a href="<b>apple</b>.com"><b>apple</b></a> and cheese</div>

如何在不更改 html 标记内部匹配项的情况下替换 html 字符串文本中出现的所有字符串?

var e = $('#cheese');
e.html(e.text().replace('apple','<b>apple</b>'));

工作小提琴

创建一个元素,在本例中为 jQuery 元素,并设置 innerHTML 属性:

var el = $('<div id="cheese" class="appleSauce"> I like apple and cheese</div>');
el.html(el.html().replace('apple','<b>apple</b>'));

你可以这样做

var str=str.replace(new RegExp(/(apple)$/),"<b>apple</b>");