Find text string in jQuery and make it bold

Solution 1:

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

Solution 2:

I had a similar problem and tried to use the solution proposed by elclanrs. It works great, but only if you have no html elements within the text you want to alter. If there were any tags inside the text, they would have been lost after running the wrapInTag function.

Here is my inner-node-friendly solution to the problem (I included links to the resources I used to write the code).

// http://stackoverflow.com/a/9795091
$.fn.wrapInTag = function (opts) {
    // http://stackoverflow.com/a/1646618
    function getText(obj) {
        return obj.textContent ? obj.textContent : obj.innerText;
    }

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

    // http://stackoverflow.com/a/298758
    $(this).contents().each(function () {
        if (this.nodeType === 3) //Node.TEXT_NODE
        {
            // http://stackoverflow.com/a/7698745
            $(this).replaceWith(getText(this).replace(regex, replacement));
        }
        else if (!opts.ignoreChildNodes) {
            $(this).wrapInTag(opts);
        }
    });
};

Example: http://jsbin.com/hawog/1/edit

Solution 3:

Try:

$(window).load(function() {
// ADD BOLD ELEMENTS
    $('#about_theresidency:contains("cross genre")').each(function(){
        $(this).html( 
            $(this).html().replace(/cross genre/g,'<strong>$&</strong>')
        );
    });
});