JS replace、replaceAll方法的实现

来源:互联网 发布:淘宝退款和售后规则 编辑:程序博客网 时间:2024/05/26 05:51
js中没有java中的replaceAll()函数,为了达到与java的replaceAll()一样的效果,我们可以用如下代码实现: 
String.prototype.replaceAll = function(s1,s2) { 
    return this.replace(new RegExp(s1,"gm"),s2); 
}
调用方式:
如想替换字符串"aa bb cc"中的所有空格,可以执行"aa bb cc".replaceAll(" ", "");
---------------------------------------------------------------------------------------------------
还有一种效率比较低的方法
while( str.indexOf( "oldstr" ) != -1 ) {
     str.replace("oldstr","newstr"); 

}



原文地址:http://lorenzooz.blog.163.com/blog/static/174240531201084113645814/

原创粉丝点击