Last updated: Mar 2, 2024
Reading timeยท2 min
The "replaceAll" is not a function error occurs when we call the
replaceAll()
method on a value that is not of type string.
To solve the error, only call the replaceAll()
method on strings in
supported browsers.
Here is an example of how the error occurs.
const value = 100; // โ๏ธ Uncaught TypeError: value.replaceAll is not a function const result = value.replaceAll('0', '9');
We called the String.replaceAll() method on a number, so the error occurred.
replaceAll()
To solve the error, convert the value to a string before calling the method.
const str = 100; const result = String(str).replaceAll('0', '9'); console.log(result); // ๐๏ธ "199"
We used the String()
constructor to convert the value to a string before
calling the replaceAll()
method.
replaceAll()
Alternatively, you can conditionally check if the value is a string, before
calling the replaceAll()
method.
const value = null; const result = typeof value === 'string' ? value.toString().replaceAll('0', '9') : ''; console.log(result); // ๐๏ธ ""
We used the ternary operator, which is very similar to an if/else
statement.
If the value is of type string, we return the result of calling the
replaceAll()
method, otherwise, we return an empty string.
You can also use a simple if
statement to check if the value is a string
before calling the replaceAll()
method.
let value2 = 'abc'; if (typeof value2 === 'string') { value2 = value2.replaceAll('abc', 'xyz'); } console.log(value2); // ๐๏ธ 'xyz'
If the value is a string, the if
block runs where we call the replaceAll()
method on the string.
replaceAll()
methodThe replaceAll()
method is not supported in Internet Explorer and some other
older browsers.
If you need to support older browsers, use the replace()
method with the g
flag instead.
const str = 'a__b'; const result = str.replace(/_/g, '#'); console.log(result); // ๐๏ธ "a##b"
The 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 a character in the string.If you ever need help reading a regular expression, check out this regular expression cheat sheet by MDN.
It contains a table with the name and the meaning of each special character with examples.
String.split()
and Array.join()
methodsIf you don't want to use a regular expression, you can use the String.split()
and Array.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 occurrence of an
underscore.
Then we joined the substrings in the array with a hash separator.
This approach achieves the same result as the replace()
method without using
regular expressions.