replace()替换文字
var test = text.innerHTML; b = test.replace(/任晓强/g,"你好"); console.log(b);
html:
<div id="text"> 任晓强去吃饭,任晓强去开车,任晓强去上班 </div>
正则:/任晓强/g可替换所有任晓强,/任晓强/只可替换第一个任晓强。
var test = text.innerHTML; b = test.replace(/(任晓强)/g,"<span class='cur'>$1</span>"); console.log(b);
text.innerHTML = b;//把b的值付给text的div
function replaceTag(str){ return str.replace(/任晓强/g,function(match){ return "<span class='cur'>"+match+"</span>"; }); } var test = text.innerHTML, b = replaceTag(test); text.innerHTML = b; console.log(b);
捕获组任晓强外要加圆括号,任晓强外加span标签,并添加高亮样式。
function replaceTag(str){ return str.replace(/[<>]/g,function(match){ switch(match){ case "<": return "<"; case ">": return ">"; } }); } var test = text.innerHTML, b = replaceTag(test); text.innerHTML = b;
替换<>成为>和<,并插入页面