Solve - replace is not a function Error in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Check out my new book

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 which caused the error.

To solve the error, convert the number to a string 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 replace().

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 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.

If the value is a string, we return the result of calling the replace method, 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 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 replace() method.

Use the search field on my Home Page to filter through my more than 3,000 articles.