三种方法:
1)str.replace(/oldstring/g,newstring);
2)str.replace(new RegExp(newstring,"gm"),newstring);
3)增加string原型方法replaceAll。
前两种里面都是正则表达式实现的,其中:
g 执行全局匹配(而非找到第一个以后就停止查找)
m 执行多行替换
方法一:
function rplcStr(){
var str = "wordwordwordwordwordword";
var newStr = str.replace(/word/g,"excel");
alert(newStr);
}
方法二:
function rplcStr(){
var str = "wordwordwordwordwordword";
var newStr = str.replace(new RegExp("word","gm"),"excel");
alert(newStr);
}
方法二:
string.prototype.replaceAll = function(s1,s2){
return this.replace(new RegExp(s1,"gm"),s2);
}