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
.
Access exclusive interactive lessons
Unlimited access to hundreds of tutorials
Remove ads to learn without distractions