使用replaceAll()替换变量在Chrome浏览器中可以正常使用,但是在IE浏览器中报错【该对象不支持replaceAll属性或方法】
js没有replaceAll()方法,但是jQuery有,但是兼容性应该比较低。
下面是在 IE 中失败的代码:
var oldTitle="" + data[i]["TITLE"] + "";
var newTitle="" + data[i]["TITLE"] + "";
todoObj =todoObj.replaceAll(oldTitle,newTitle);
角色替换:
如果用js正常替换的话echarts 浏览器兼容echarts 浏览器兼容,字符替换,s被b替换
string.replace('s', 'b'); // 只能替换第一个匹配到的
string.replace(/s/g, 'b'); // 使用正则加参数 g,进行全文匹配而不是匹配到第一个后停止
变量替换:
var str = 's';
string.replace(str, "b"); // 替换第一个匹配的
string.replace(new RegExp(str, 'gm'), "b");
向字符串对象添加replaceAll()方法
// prototype:增加一个属性
String.prototype.replaceAll = function(s1, s2){
// g:执行全局匹配,而不是匹配第一个后停止。
// m:执行多行匹配
return this.replace(new RegExp(s1,"gm"),s2);
};
替换后的代码没有错误:
var oldTitle="" + data[i]["TITLE"] + "";
var newTitle="" + data[i]["TITLE"] + "";
todoObj = todoObj.replace(new RegExp(oldTitle, 'gm'),newTitle);
过了一会儿,问题又出现了。 另一种方式,使用 split 和 join
var oldTitle="" + data[i]["TITLE"] + "";
var newTitle="" + data[i]["TITLE"] + "";
todoObj = todoObj.split(oldTitle).join(newTitle);