日期:2014-05-16  浏览次数:20330 次

js javaScript中String添加replaceAll 方法
String.prototype.replaceAll = function(s1, s2) {    
    return this.replace(new RegExp(s1, "gm"), s2); //g全局   
}   
  
String.prototype.replaceAll2Excep = function(s1, s2) {      
    var temp = this;      
    while (temp.indexOf(s1) != -1) {      
        temp = temp.replace(s1, s2);      
    }      
    return temp;      
}    
alert("abcedaaabs".replaceAll("a", "A"));   
alert("abcedaaabs".replaceAll2Excep ("a", "A")); 

?

1 楼 chunchong 2011-10-18  
如果s1中有([\(\)\[\]\{\}\^\$\+\-\*\?\.\"\'\|\/\\])第一种方法会出问题,从别人那看到如下处理
String.prototype.replaceAll = function(AFindText, ARepText) {
var raRegExp = new RegExp(AFindText.replace(
/([\(\)\[\]\{\}\^\$\+\-\*\?\.\"\'\|\/\\])/g, "\\$1"), "ig");
return this.replace(raRegExp, ARepText);
}