您可以使用 JQuery包含选择器,如下所示:
http://jsfiddle.net/z4ZwF/
function replaceText(textToSearch,classToApply)
{
$('div').html($('div').html().replace(new RegExp(textToSearch, 'g'),"<span class='"+classToApply+"'>"+textToSearch+"</span>"));
}
示例:replaceText("'lorem ipsum'",'red')
或replaceText("line",'red')
编辑
在搜索和替换中添加引号包装:http: //jsfiddle.net/z4ZwF/3/
function replaceText(textToSearch,classToApply,searchAndWrapQuote)
{
searchAndWrapQuote = searchAndWrapQuote || false;
quote = (searchAndWrapQuote) ? "'" : "";
$('div').html($('div').html().replace(new RegExp(quote+textToSearch+quote, 'g'),"<span class='"+classToApply+"'>"+quote+textToSearch+quote+"</span>"));
}
replaceText("lorem ipsum",'red',true)