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

Why Does This Happen?

If you're seeing the error "TypeError: replaceAll is not a function", it is likely due to the method not implemented/supported by the browser version (or the Node.js version) that you're using.

Note that the String.prototype.replaceAll() method was added in ES2021/ES12.

How to Fix the Issue?

As a substitute for String.prototype.replaceAll(), you may use the String.prototype.replace() method with a regular expression that has the global ("g") flag set. It works in the same way and has great browser support.

The following example shows replaceAll() and it's equivalent using replace():

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);

For more examples, check out our post about how to replace all occurrences of a word in a JavaScript string.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.