你可以用replace()
与html()
:
var html = $('p').html();
$('p').html(html.replace(/world/gi, '<strong>$&</strong>'));
$.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']
});