Francis Snipe
Francis Snipe

Reputation: 551

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?

Upvotes: 1

Views: 4414

Answers (3)

Alex
Alex

Reputation: 35407

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>'));

Upvotes: 1

Michael Brenndoerfer
Michael Brenndoerfer

Reputation: 4096

You can do it like that

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

Upvotes: 0

Oswaldo Acauan
Oswaldo Acauan

Reputation: 2740

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

Working Fiddle

Upvotes: 1

Related Questions