TypeError: replace is not a function in JavaScript

TypeError: .replace is not a function occurs when we call replace() function on object which is not an string. replace() function can be only called on string. To resolve this issue, convert value to string using toString() ,method before calling replace() method.

Let’s see with help of simple example where we want to remove . from number.

For example: 1.23 should become 123.

You will get following error when you execute the program:

We got this error because num is not an string, it is number.

Convert num to string using toString() method and it will work fine.

Output:

You can also check if it is type of string before calling replace() to make sure that replace() is being called on string only.

Output:

As you can see num is not a string, so result is empty string.

We used ternary operator to check if num is string or not. If it is a string, call the replace method, otherwise return empty string.

Read also: map is not a function in JavaScript.

That’s all about how to resolve TypeError: replace is not a function in JavaScript.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *