Tue Oct 19 2021·2 min read
Photo by Jeremy Perkins
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.
Here is an example of how the error occurs.
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.
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
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 the value is of type string, we return the result of calling the
method on it, otherwise we return an empty string.
replaceAllmethod is not supported in Internet Explorer. If you need to support the browser, use the
replacemethod with the
const str = 'a__b'; const result = str.replace(/_/g, '#'); console.log(result); // 👉️ "a##b"
replace method takes 2 parameters:
The forward slashes mark the beginning and end of the regular expression.
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.
join()methods to achieve the same result.
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
Then we joined the substrings of the array with a hash separator.
replace()method and enables us to avoid using regular expressions.
I'll send you 1 email a week with links to all of the articles I've written that week