js實現字串替換replaceAll的方法
阿新 • • 發佈:2019-02-07
JS 字串替換操作有replace() 方法。但是這個方法有些問題,就是隻能替換目標字串中第一個匹配的字串。 如下例:
var str = "wordwordwordword";
var strNew = str.replace("word","Excel");
alert(strNew);
如果要將目標字串全部替換的話,java裡可以用replaceAll,但是JS 沒有提供這樣的方法。使用正則表示式可以達到replaceAll的效果:
str.replace(/word/g,"Excel") ;
g 的意義是:執行全域性匹配(查詢所有匹配而不是在找到第一個匹配後停止)。
function replaceAll(str) { if(str!=null) str = str.replace(/word/g,"Excel") return str; } var str = "wordwordwordword"; var strNew = str.replace("word","Excel"); strNew = replaceAll(str); alert(strNew);
以上寫法有個相似的寫法:
str.replace(new RegExp("word","gm"),"Excel")
g 執行全域性匹配(查詢所有匹配而非在找到第一個匹配後停止)。
m 執行多行匹配。
除此之外,也可以新增 Stirng物件的原型方法,這樣就可以隨時向使用relpace一樣使用replaceAll:
String.prototype.replaceAll = function(s1,s2){
return this.replace(new RegExp(s1,"gm"),s2);
}
這樣就可以像使用replace 方法一樣使用replaceAll了。
str.replaceAll("word","Excel");
總結一下:
1. str.replace(/oldString/g,newString)
2. str.replace(new RegExp(oldString,”gm”),newString)
3. 增加String 物件原型方法 replaceAll