Last updated: Jul 25, 2022
Check out my new book
The "replace is not a function" error occurs when we call the
method on a value that is not of type
string. To solve the error, convert the
value to a string using the
toString() method before calling the
Here is an example of how the error occurs.
const num = 10; // ⛔️ Uncaught TypeError: num.replace is not a function const result = num.replace(/[0-9]/g, '-')
We called the String.replace method on a number which caused the error.
To solve the error, convert the number to a string before calling the
const num = 10; // ✅ call toString() first const result = num.toString().replace(/[0-9]/g, '-'); console.log(result); // 👉️ "--"
We used the
toString() method to convert the number to a string before calling
Alternatively, you can conditionally check if the value is a string before
const num = 10; const result = typeof num === 'string' ? num.replace(/[0-9]/g) : ''; console.log(result); // 👉️ ""
We used the ternary operator to check if the
num variable stores a string.
If it does, the value to the left of the comma is returned, otherwise the value to the right is returned.
replacemethod, otherwise we return an empty string to be consistent.
If the error persists,
console.log the value you're calling the
method on and use the
typeof operator to check its type.
If the value is an object, there's a very good chance that you are forgetting to
access a specific property, on which you need to call the