Reputation: 139
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>');
});
Upvotes: 0
Views: 106
Reputation: 253308
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>');
});
Upvotes: 3
Reputation: 4294
You could use a regex replace:
$('p').html($('p').text().replace(/(ain)/gi, '<span class="red">$1</span>'));
Upvotes: 0