How to solve replace is not a function in JavaScript
In this tutorial, we are going to learn about how to solve the TypeError: replace is not a function in JavaScript
When we use a ‘replace()’ method on a value which is not a data type string we will get the following error in our console.
Example:
const value = 8999;
console.log(value.replace(/[0-9]/g, 2));
Output:
"TypeError: value.replace is not a function
In the example above, we are getting the error because we are using the ‘replace()’ method on a datatype number, but the replace method is only available on the string datatype.
To solve the “TypeError: replace is not a function”, make sure to call the replace() method on a data type string or convert the number to string before calling the replace() method on it.
Here is an example:
const value = 8999;
const result = value.toString().replace(/[9]/g, 2);
console.log(result);
Output:
'8222'
In the example above, we first converted the given value to a string using the toString() method, then we called a replace() method on it to replace the 9 with 2.
Note: The ‘replace()’ method creates a new string with the replacement values that matches the regex pattern, in our case we have replaced all 9’s in the string with 2.
Type checking
To avoid the run time errors, we can also check the given datatype is a string or not before calling the replace() method on it.
Here is an example:
const value = 8999;
if(typeof value === 'string'){
console.log(value.replace(/[9]/g, 2));
}else{
console.log('Given value is not a string');
}
Conclusion
The “replace is not a function” error occurs, when we call a replace() method on a value which is not string. To solve the error convert the value to an string before calling the replace() method on it or make sure to use the replace() method on valid strings.