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.
1 2 3 4 5 |
var num=1.23; num=num.replace(/\./g,''); console.log(num); |
You will get following error when you execute the program:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
num=num.replace(/\./g,''); ^ TypeError: num.replace is not a function at Object.<anonymous> (HelloWorld.js:2:9) at Module._compile (internal/modules/cjs/loader.js:959:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10) at Module.load (internal/modules/cjs/loader.js:815:32) at Function.Module._load (internal/modules/cjs/loader.js:727:14) at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10) at internal/main/run_main_module.js:17:11 |
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.
1 2 3 4 5 |
var num=1.23; num=num.toString().replace(/\./g,''); console.log(num); |
Output:
1 2 3 |
123 |
You can also check if it is type of string before calling replace() to make sure that replace()
is being called on string only.
1 2 3 4 5 |
var num=1.23; num=typeof num === 'string' ?num.replace(/\./g,''):''; console.log(num); |
Output:
1 2 3 |
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
.