JavaScript中是没有replaceAll的,只有replace,replace只能替换字符中的第一个字符,而且这个replace里面不支持正则表达式,以达到replaceAll的目的。
不过可以自己写一个JavaScript中的replaceAll,也不用写到str.replaceAll,一点就能够用的程度的程度,写一个返回值为字符串类型、处理之后的字符串;形式参数为要处理的字符串,要被替换的东西、要被替换成的东西的函数就可以了。
写好一个JavaScript中的replaceAll可以对某些多行文本框从数据库读取数据,之后清理多行文本框不能被javascript中清理HTML函数,详见《【JavaScript】某些字符不转义可以导致网页崩溃与涉及转义字符的显示方法》(点击打开链接),把<BR>清理成\r\n的问题,从而在多行文本框正常显示的问题。这多见于一些编辑功能。
JavaScript的replaceAll函数如下:
function replaceAll(str,replaced,replacement){
var reg=new RegExp(replaced,"g");
str=str.replace(reg,replacement);
return str;
}
具体使用方式用一个例子来说明这个函数的利用,
比如网站有如下的表单,显示如同word中的替换功能。
这个网页的布局如下,很简单,请注意里面的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 οnclick="replaceAllTest()">go!</button>
</body>
</html>
GO按钮首先调用脚本中的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>