【JavaScript】JavaScript中的replaceAll

JavaScript中是没有replaceAll的。仅仅有replace,replace仅仅能替换字符中的第一个字符。并且这个replace里面不支持正則表達式,以达到replaceAll的目的。

只是能够自己写一个JavaScript中的replaceAll,也不用写到str.replaceAll,一点就能够用的程度的程度。写一个返回值为字符串类型、处理之后的字符串;形式參数为要处理的字符串,要被替换的东西、要被替换成的东西的函数就能够了。

写好一个JavaScript中的replaceAll能够对某些多行文本框从数据库读取数据,之后清理多行文本框不能被javascript中清理HTML函数。详见《【JavaScript】某些字符不转义能够导致网页崩溃与涉及转义字符的显示方法》(点击打开链接),把<BR>清理成 的问题,从而在多行文本框正常显示的问题。

这多见于一些编辑功能。

JavaScript的replaceAll函数例如以下:

function replaceAll(str,replaced,replacement){
	var reg=new RegExp(replaced,"g");
	str=str.replace(reg,replacement);
	return str;
}

详细使用方式用一个样例来说明这个函数的利用,

比方站点有例如以下的表单。显示如同word中的替换功能。


这个网页的布局例如以下,非常easy,请注意里面的ID就可以:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>replaceAll</title>
</head>

<body>
<textarea id="str"></textarea><br />
把<input type="text" id="replaced" />替换成<input type="text" id="replacement" /><button onclick="replaceAllTest()">go!</button>
</body>
</html>

GObutton首先调用脚本中的replaceAllTest函数,把文本框中的内容,被替换的内容,要替换的内容拿过来。直接调用上文的replaceAll()函数,完毕替换得到的字符串,则替换文本框中的文本就可以。

<script>
function replaceAllTest(){
	var str=document.getElementById("str").value;
	var replaced=document.getElementById("replaced").value;
	var replacement=document.getElementById("replacement").value;
	str=replaceAll(str,replaced,replacement);
	document.getElementById("str").value=str;
}
function replaceAll(str,replaced,replacement){
	var reg=new RegExp(replaced,"g");
	str=str.replace(reg,replacement);
	return str;
}
</script>


原文地址:https://www.cnblogs.com/cynchanpin/p/7011124.html