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="替换后字符"/>&nbsp;&nbsp;&nbsp;
<input type="button" id="btnFind" value="替换"/>&nbsp;&nbsp;&nbsp;<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+val.length+12;
			}
			
		}
		else
		{
			if(txt.substring(i,i+val.length)==val)
			{
				inner=txt.split('');
				inner.splice(i,val.length,newInner);
				txt=inner.join("");
				i=i+val.length+12;
			}
		}
	}
	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>

欢迎分享本文,转载请保留出处:前端ABC » JS 文本中查找并替换字符

赞 (1)
分享到:更多 ()

发表评论 0