當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
JS实现文本中查找并替换字符
生活随笔
收集整理的這篇文章主要介紹了
JS实现文本中查找并替换字符
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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>
?如有錯誤,歡迎聯系我改正,非常感謝!!!
更多專業前端知識,請上 【猿2048】www.mk2048.com
總結
以上是生活随笔為你收集整理的JS实现文本中查找并替换字符的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JQ实现弹幕效果
- 下一篇: 使用JS实现文字搬运工