0

Is there a way to perform a search some HTML and whenever it finds an occurrence of a regular expression, wrap it in a span?

For example:

<p>The rain in Spain stays mainly on the plain</p>

$('p').match('/ain/gi').each(function() {
  $(this).wrap('<span class="red"></span>');
});
Devin
  • 7,690
  • 6
  • 39
  • 54
increase Mather
  • 139
  • 2
  • 6
  • I think contains() should work for you something like var foundin = $('p:contains("I am a simple string")');. see here http://stackoverflow.com/questions/926580/find-text-string-using-jquery – RN Kushwaha Sep 15 '14 at 19:26

2 Answers2

3

I'd strongly suggest the following, simpler, approach:

// selects the 'p' elements, and calls the 'html()' method:
$('p').html(function (i,h) {
    // uses the anonymous function, i is the index of the current element
    // from the collection, h is the found HTML of that element.
    return h.replace(/(ain)/gi, '<span class="red">$1</span>');
});
David Thomas
  • 249,100
  • 51
  • 377
  • 410
0

You could use a regex replace:

$('p').html($('p').text().replace(/(ain)/gi, '<span class="red">$1</span>'));

http://jsfiddle.net/husgns7t/

Tom Pietrosanti
  • 4,184
  • 2
  • 24
  • 29
  • Very true. I was only trying to demonstrate the replacement part given a single element selection, and didn't consider more than a single element selection. – Tom Pietrosanti Sep 16 '14 at 02:21