低版本浏览器普遍不支持replaceAll, 所以谨慎使用此方法。
如图,replaceAll() 报错了,查看了下当前chrome浏览器的版本,发现Chrome版本太低,故判定原因为低版本浏览器不支持字符串的replaceAll();
解决replaceAll 不兼容问题方法:
1. 用replace替代
//replace 默认只会匹配替换到匹配到的第一个,因此要加 / /g
let newStr = string.replace(/oldString/g, newString);
2. 第二种也是用replace方法
let newStr = string.replace(new RegExp( "oldString", "gm" ),"newString");
// gm:g=global, m=multiLine 可以实现替换全部指定字串
3. 给String对象扩展原型方法 replaceAll
String.prototype.replaceAll = function(newString, oldString) {
return this.replace(new RegExp("oldString","gm" ),"newString" );
}
replace 和 replaceAll 有什么区别呢?
replaceAll(pattern, replacement) 返回一个新字符串,不会改变原字符串;替换所有匹配到的字符串;
replace(pattern, replacement) 返回一个新字符串,替换其中一个或部分字符串;