JS实现文本中查找并替换字符
效果图:
代码如下,复制即可使用:
<!DOCTYPE html>
<html> <head> <style type="text/css"> *{font-family:"微软雅黑";font-size:16px;margin:0;padding:0;letter-spacing:3px;line-height:22px;} #wrap{width:500px;height:300px;margin:20px auto;position:relative;} #text{width:500px;height:300px;border:1px solid green;} #result{width:500px;position:absolute;left:0px;top:0px;display:none;} input{width:100px;height:40px;margin-top:5px;} span{background-color:yellow;} </style> </head> <body> <div id="wrap"> <div id="result"></div> <textarea id="text" placeholder="请在此输入文本。。。。"></textarea> <input type="text" id="val" placeholder="被查找字符"/>——<input type="text" id="new_val" placeholder="替换后字符"/> <input type="button" id="btnFind" value="替换"/> <input type="button" value="重置" id="reset"/> </div> <script type="text/javascript"> function replace(){ var inner=null; var txt=document.getElementById('text').value.toString(); var val=document.getElementById('val').value.toString(); var newVal=document.getElementById('new_val').value.toString(); newInner="<span>"+newVal+"</span>"; for(var i=0;i<=txt.length-val.length;i++){ if(txt==""||val=="") { alert("请输入内容!"); return false; } if(txt.length<val.length) { return false; } if(i+val.length>=txt.length){ if(txt.substring(i)==val){ inner=txt.split(''); inner.splice(i,val.length,newInner); txt=inner.join(""); i=i+newInner.length-1; } } else { if(txt.substring(i,i+val.length)==val) { inner=txt.split(''); inner.splice(i,val.length,newInner); txt=inner.join(""); i=i+newInner.length-1; } } } document.getElementById("result").innerHTML=txt; document.getElementById("text").value=null; document.getElementById("text").placeholder=""; document.getElementById("result").style.display="block"; } document.getElementById('btnFind').onclick=function(){ replace(); } document.getElementById('reset').onclick=function(){ document.getElementById("result").style.display="none"; document.getElementById("val").value=null; document.getElementById("new_val").value=null; document.getElementById("text").placeholder="请在此输入文本。。。。"; } </script> </div> </body> </html>
如有错误,欢迎联系我改正,非常感谢!!!