简体   繁体   中英

Adding bold tags to a string of html

I have a string of html in javascript/jquery.

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

I want to make the string 'apple' bold. So I do:

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

but this breaks the html part of the string. I get:

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

How can I replace all occurrences of a string in the text of an html string without changing the matches inside of html markup?

Create an element, jQuery element in this case, and set the innerHTML property:

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

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

Working Fiddle

你可以那样做

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM