If you see the error TypeError: replaceAll is not a function
, it may be that your browser version or Node.js version does not support this method.
What we should pay attention to is: String.prototype.replaceAll()
method was added in ES2021/ES12, and it is very likely that the environment does not support it.
You can use String.prototype.replace()
as a substitute for String.prototype.replaceAll()
. replace()
only needs to set a global (g
) in the replacement regular expression. In this way, the result of replaceAll()
is the same. Let's look at a comparison example:
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);