怎么修复 "replaceAll is not a function" JavaScript Error?

为什么会出现上面的报错情况

如果你看到了“TypeError: replaceAll is not a function”这个错误,可能是你的浏览器版本或者Node.js版没有支持此方法。

我们要注意的是:String.prototype.replaceAll() 方法是在ES2021/ES12中被加入的,很有可能的环境不支持。

怎么解决呢?

你可以使用“String.prototype.replace()”作为“String.prototype.replaceAll()”的替代品,replace() 只需要在替换的正则表达式中设置一个全局(g)就可以了。这种处理方式了replaceAll()的处理结果相同。下面来看个对比的例子:

const str = 'foo-bar';

// in older browsers
const result1 = str.replace(/foo/g, 'moo');

// ES12+
const result2 = str.replaceAll('foo', 'moo');

// output: 'moo-bar'
console.log(result1);
console.log(result2);

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章