今天在做项目的时候,发现PC微信内置浏览器使用replaceAll无反应,微信开发工具没有问题,就是这个微信内置浏览器,也不报错,只是执行到此就bug掉了
既然不支持replaceAll这样的方法,那可以换成了使用正则表可以达成ReplaceAll 的效果:
str.replace(/word/g,"Excel");
g 的意义是:执行全局匹配(查找所有匹配而非在找到第一个匹配后停止)。
var str = "wordwordwordword";
var strNew = str.replace(/word/g,"Excel")
strNew = replaceAll(str);
还有一种方式:
str.replace(new RegExp("word","gm"),"Excel")
g 执行全局匹配(查找所有匹配而非在找到第一个匹配后停止)。
m 执行多行匹配。
str.replace(new RegExp("word","gm"),"Excel")
除此之外,也可以添加 Stirng对象的原型方法:
String.prototype.replaceAll = function(s1,s2){
return this.replace(new RegExp(s1,"gm"),s2);
}
这样就可以像使用replace 方法一样使用replaceAll了
str.replaceAll("word","Excel");
三种方式如下:
- str.replace(/oldString/g,newString)
- str.replace(new RegExp(oldString,"gm"),newString)
- 增加String 对象原型方法 replaceAll