您可以使用jQuery contains選擇這樣的代碼:
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)
新增小提琴http://jsfiddle.net/z4ZwF/ – sdespont
但是如果我不得不申請的CSS的所有單詞,包括那些引號中引號? –
附上用引號像replaceText文本(「‘Lorem存有’」,「紅」)http://jsfiddle.net/z4ZwF/2/ – sdespont