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

Ferenc Almasi β€’ 2022 November 10 β€’ Read time 1 min read
  • twitter
  • facebook
JavaScript

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.

Copied to clipboard! Playground
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

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.

Copied to clipboard! Playground
// ❌ Instead of using replaceAll
value.replaceAll('-', '/')

// βœ”οΈ Use replace with a regex
value.replace(/-./g, '/')
Using replace with a regular expression in place of replaceAll

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.

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.