Satyajyoti Biswas
Satyajyoti Biswas

Reputation: 957

How to replace a part of a string with a html tag?

How to replace a part of a string with a html tag in jQuery?
Say for e.g. <div>Who am i</div> should be <div><b>Who</b> am i</div>.

Upvotes: 4

Views: 133

Answers (2)

Ram
Ram

Reputation: 144729

You can use html method's callback function and replace method.

$('div').html(function(_, oldHTML){
   return oldHTML.replace(/(\w+)/, '<b>$1</b>');
   // return oldHTML.replace('Who', '<b>Who</b>');
})

http://jsfiddle.net/3rAMp/

Upvotes: 4

Cris
Cris

Reputation: 13351

use .html() of jquery

$("div").html("<b>Who</b> am i")

Upvotes: 1

Related Questions