πŸŽ„ Get 50% off from our JavaScript course for the holidays! πŸŽ„

How to Fix "replaceAll is not a function" Errors in JS

Ferenc Almasi β€’ 2022 November 10 β€’ πŸ“– 1 min read

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()
Only call replaceAll on strings
Copied to clipboard!

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, '/')
Using replace with a regular expression in place of replaceAll
Copied to clipboard!

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.

Share on
  • twitter
  • facebook
JavaScript Course Dashboard

Tired of looking for tutorials?

You are not alone. Webtips has more than 400 tutorials which would take roughly 75 hours to read.

Check out our interactive course to master JavaScript in less time.

Learn More

Recommended

πŸŽ‰ Thank you for subscribing to our newsletter. x