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']
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…