您好,欢迎光临! 推荐您使用Chrome浏览器访问本站。

JavaScript replace函数 替换所有相同字符

最近有个需求是在javascript中将所有相同字符批量替换,虽然知道有replace函数但默认只能替换一个字符,不能替换所有,求助网络后得知采用正则表达式可实现此功能。
格式:replace(/被替换内容/g,'替换内容');
var obj=document.body;
var fieldsname="",fieldsvalue="";
<pre>var reas = document.getElementById(obj.id).getElementsByTagName("textarea");

for(var i=0;i<reas.length;i++){
 fieldsname+=","+reas[i].name;
 fieldsvalue+=","+reas[i].value.replace(/,/g,",");
//replace(/,/g,",")将半角逗号(,)替换成全角逗号(,)
// /,/g 为正则表达式模式
 }

参考:

http://www.w3school.com.cn/js/jsref_replace.asp
http://www.ijavascript.cn/shouce/javascript-replace-292.html
http://www.cnblogs.com/leochu2008/archive/2008/04/28/1174400.html

您可能也喜欢