Solve - replace is not a function Error in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

banner

Photo by Jaxon Lott

Solve - replace is not a function Error #

The "replace is not a function" error occurs when we call the replace() 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 replace() method.

replace is not a function

Here is an example of how the error occurs.

index.js
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 and got the error back.

To solve the error, convert the string to a number before calling the replace() method.

index.js
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 the replace method.

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

index.js
const num = 10; const result = typeof num === 'string' ? num.replace(/[0-9]/g) : ''; console.log(result); // ๐Ÿ‘‰๏ธ ""

We used a 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.

If the value is a string, we return the result from calling the replace method on it, otherwise we return an empty string to be consistent.

If the error persists console.log the value you're calling the replace method on and check it's type using the typeof operator.

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 replace() method.

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