4种写法解决IE不支持replaceAll
前言
使用 replaceAll()
替换变量在 Chrome 浏览器中可以正常使用,在 IE 浏览器中报错【对象不支持 replaceAll 属性或方法】
1、使用replace()全局替换写法一
使用replace全局替换,可以把所有匹配字符全替换,代码如下:
var re = /apples/gi;
var str = "Apples are round, and apples are juicy.";
var newstr = str.replace(re, "oranges");
alert(newstr);
// 返回: oranges are round, and oranges are juicy.
在replace()中使用global和ignore选项,正则表达式包含有全局替换(g)和忽略大小写(i)的选项,这使得replace方法用“oranges”替换掉了所有出现的“apples”。
2、使用replace()全局替换写法二
下面是使用replace()全局替换的第二种写法,功能与写法一是一样的。
var str = "Apples are round, and apples are juicy.";
var newstr = "";
newstr = str.replace(new RegExp("apples", "gi"),"oranges");
alert(newstr);
// 返回:oranges are round, and oranges are juicy.
3、创建String原型对象
创建一个String原型对象,可以在IE使用replaceAll实现字符全替换功能。代码如下:
(function(){
//if (!String.prototype.hasOwnProperty("replaceAll")){
String.prototype.replaceAll = function(s1,s2){
return this.replace(new RegExp(s1,"gim"),s2); //g全局 i忽略字母大小写 m多行
};
//}
})();
var re = "apples";
var str = "Apples are round, and apples are juicy.";
var newstr = str.replaceAll(re, "oranges");
alert(newstr);// 返回: oranges are round, and oranges are juicy.
x
4、使用 split() 和 join()
使用split()和join()的方法同样可以实现字符全替换功能,写法也非常简单,代码如下:
var str = "Apples are round, and apples are juicy";
str = str.split(/apples/i).join('oranges');
alert(str);// 返回: oranges are round, and oranges are juicy.
注意:split()分割默认是区分字母大小写的,所以需要忽略大小写时要按本示例那样写。
总结
本文介绍了4种写法解决IE不支持replaceAll的问题,并且在IE11、Chrome、Firefox等主流浏览器上测试通过。