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

如果你看到了“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);

 

相关文章:

  • 2021-11-03
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-25
  • 2021-07-05
  • 2021-08-08
猜你喜欢
  • 2022-12-23
  • 2021-12-06
  • 2021-09-07
  • 2021-08-12
  • 2022-12-23
  • 2022-12-23
  • 2021-06-20
相关资源
相似解决方案