Find text string in jQuery and make it bold

You can use replace() with html():

var html = $('p').html();
$('p').html(html.replace(/world/gi, '<strong>$&</strong>'));

Edit: http://jsbin.com/AvUcElo/1/edit

I turned it into a lil’ plugin, here:

$.fn.wrapInTag = function(opts) {

  var tag = opts.tag || 'strong'
    , words = opts.words || []
    , regex = RegExp(words.join('|'), 'gi') // case insensitive
    , replacement="<"+ tag +'>$&</'+ tag +'>';

  return this.html(function() {
    return $(this).text().replace(regex, replacement);
  });
};

// Usage
$('p').wrapInTag({
  tag: 'em',
  words: ['world', 'red']
});

Leave a Comment