How to fix "replaceAll is not a function" JavaScript Error?

created at 10-27-2021 views: 1

Why this error reported

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.

How to solve 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'
Please log in to leave a comment.