在java中,字符串可以使用replaceAll進行全局替換,類似於正則表達式中使用了/g的全部控制變量。但是js字符串(String)本身是不支持replaceAll方法的,只能使用簡單的replace方法,如下所示:
1 var a = "xxxxx"; 2 alert(a.replace("x","a")); //返回 axxxx
很顯然,用簡單的replace只能替換第一個匹配項,這可能對某些需求不太方便。當然,也可以通過如下的方式,實現全局的替換:
1 var a = "xxxxx"; 2 alert(a.replace(/x/g,"a")); //返回 aaaaa
但是優秀的程序員人都是“懶惰”的,我們不想每次全局替換的時候都用正則的方式來實現,有沒有一種一勞永逸的方法呢?答案是肯定的,只需要在代碼中加入如下代碼(摘自網絡):
1 String.prototype.replaceAll = function(reallyDo, replaceWith, ignoreCase) { 2 if (!RegExp.prototype.isPrototypeOf(reallyDo)) { 3 return this.replace(new RegExp(reallyDo, (ignoreCase ? "gi": "g")), replaceWith); 4 } else { 5 return this.replace(reallyDo, replaceWith); 6 } 7 }
這里為String添加了一個函數(相當與添加了native Code)replaceAll。
(String | RegExp)reallyDo代表被替換的字符串,(String)replaceWidth代表替換的字符串,(Boolean)ignoreCase為是否忽略大小寫。
在之后的js代碼中就可以直接使用replaceAll方法了。
1 var a = "xxxxx"; 2 alert(a.replaceAll("x","a")); //返回 aaaaa