目的:把一段字符串里的指定字符全部替換或者刪除。
tips:刪除只需要把后面的值改為 " " 即可
1.replace基礎用法:
string.replace("a","b"); //把string里面的第一個'a'替換成'b';
2.全局替換固定字符:
// 正則加個參數 g ,表示全文匹配。 string.replace(/a/g,"b"); //把string里面的所有'a'替換成'b';
3.全局替換變量:
//這是正則的另一種寫法,利用JS的 RegExp 對象,將 g 參數單拿了出來 string.replace(new RegExp(key,'g'),"b"); //傳一個變量key,把string里面的所有key值替換成'b'
4.封裝函數:
function replaceAll(str,preVal,replaceVal){ return str.replace(new RegExp(preVal,'g'),replaceVal); } replaceAll("你你我我他他","他",""); // "你你我我" replaceAll("你你我我他他","他","它"); // "你你我我它它"
5.雖然封裝了函數,但是感覺有點繁瑣,讓我們在String的原型鏈上添加方法,調用起來更方便:
String.prototype.replaceAll=function(preVal,replaceVal){ return this.replace(new RegExp(preVal,'g'),replaceVal); } var a ="你你我我他他"; a.replaceAll("他","") //你你我我 a.replaceAll("他","它") //你你我我它它 String("12341234").replaceAll("34",""); //1212
