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