Solve - replaceAll is not a function Error in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

Solve - replaceAll is not a function Error #

The "replaceAll" is not a function error occurs when we call the replaceAll() method on a value that is not of type string or in a browser that doesn't support it. To solve the error, only call the replaceAll() method on strings in supported browsers.

typeerror-replaceall-is-not-a-function

Here is an example of how the error occurs.

index.js
const str = 100; // โ›”๏ธ Uncaught TypeError: str.replaceAll is not a function const result = str.replaceAll('0', '9');

We called the String.replaceAll method on a number and got the error back.

To solve this, you can convert the value to a string before calling the method.

index.js
const str = 100; // โ›”๏ธ Uncaught TypeError: str.replaceAll is not a function const result = str.toString().replaceAll('0', '9'); console.log(result); // ๐Ÿ‘‰๏ธ "199"

Alternatively, you can conditionally check if the value is a string, before calling the replaceAll method.

index.js
const str = null; const result = typeof str === 'string' ? str.toString().replaceAll('0', '9') : ''; console.log(result); // ๐Ÿ‘‰๏ธ ""

We used a ternary operator, which is very similar to en if/else statement.

If the value is of type string, we return the result of calling the replaceAll method on it, otherwise we return an empty string.

The replaceAll method is not supported in Internet Explorer. If you need to support the browser, use the replace method with the g flag instead.
index.js
const str = 'a__b'; const result = str.replace(/_/g, '#'); console.log(result); // ๐Ÿ‘‰๏ธ "a##b"

The replace method takes 2 parameters:

  • a regular expression we want to match in the string
  • the replacement for each match

The forward slashes mark the beginning and end of the regular expression.

We used the g (global) flag because we want to replace all occurrences of an underscore in the string with a hash.

If you ever need help reading a regular expression, check out this regex cheatsheet from MDN. It's by far the best one out there.

If you don't want to use a regular expression, you can use the split() andjoin() methods to achieve the same result.
index.js
const str = 'a__b'; const result = str.split('_').join('#'); console.log(result); // ๐Ÿ‘‰๏ธ "a##b"

We used the split() method to split the string on each underscore into an array.

Then we joined the substrings of the array with a hash separator.

This approach achieves the same result as the replace() method and enables us to avoid using regular expressions.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee