Why Does This Happen?
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
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);
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.