记一次replaceAll报错的问题

140 阅读1分钟

产生原因

公司大屏在国产机运行不正常,但是运行后台端都正常

排查问题

a.replaceAll() is not a function

查了下MDN

image.png

解决问题

可以使用replace去替换

image.png

//方法一 直接替换
const str = "Hello World, Hello Universe";
const newStr = str.replace(/Hello/g, "Hi");
console.log(newStr); // 输出: "Hi World, Hi Universe


//或者使用函数
function replaceAll(str, search, replacement) {
    let result = str;
    while (result.includes(search)) {
        result = result.replace(search, replacement);
    }
    return result;
}

const str = "Hello World, Hello Universe";
const newStr = replaceAll(str, "Hello", "Hi");
console.log(newStr); // 输出: "Hi World, Hi Universe"
//方法二   如果不兼容使用改造方法
if (!String.prototype.replaceAll) {
  String.prototype.replaceAll = function (newStr, oldStr) {
    return this.replace(new RegExp("oldStr", "g"), "newStr");
  };
}