JS 文本中查找并替换字符
<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>
WEB前端学习交流群21 598399936 |
相关推荐
- JS 文本中查找并替换字符
- 使用sed命令查找和替换文件中的字符串的16个示例
- Adobe Acrobat如何查找并替换文本
- 在js中将日期转换为字符串_如何在Word 2013中将文本转换为表格并将表转换为文字...
- excel在文本加引用数字_如何在Excel中查找和替换文本和数字
- js 中替换全部字符串
- Notepad++中把查找到的字符替换成回车换行符和\n和\r的区别?
- 【超详细图解】字符串匹配Boyer-Moore算法:文本编辑器中的查找功能是如何实现的?
- c# word中替换字符_如何在Microsoft Word中查找和替换特殊字符
- 如何利用正则表达式中的查找替换在前面添加字符
- 网络性能拨测-网络传输速度体验检测系统有那些指标?
- rocketmq——通过学习后对于rocketmq分布式事务的理解