How to Fix "replaceAll is not a function" Errors in JS
The "replaceAll is not a function" error can happen for two reasons. The replaceAll
function is only available on strings. Therefore, if the value you are using turns out to be anything other than a string, you are going to get the error. To fix this, make sure you are calling replaceAll
on a string.
const value = []
// β This will throw "replaceAll is not a function"
value.replaceAll()
// βοΈ Check the type before using the function
if (typeof value === 'string') {
value.replaceAll()
}
// βοΈ Convert the value to a string beforehand
String(value).replaceAll()
The other reason this can happen is when you are using an older version of Node. The replaceAll
function is only available from Node v15. If you are using a lower version, you are going to run into the error. To get around this, either update your node version if possible or use replace
with a global regex.
// β Instead of using replaceAll
value.replaceAll('-', '/')
// βοΈ Use replace with a regex
value.replace(/-./g, '/')
Support-wise replace
is also more widely supported than replaceAll
. In case you need to keep older browsers supported, it is worth going with replace
over replaceAll
.
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: