How to solve trim is not a function in JavaScript
In this tutorial, we are going to learn about how to solve the TypeError: trim is not a function in JavaScript
When we use a ‘trim()’ 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.trim(0, 2));
Output:
"TypeError: value.trim is not a function
In the example above, we are getting the error because we are using the ‘trim()’ method on a datetype number, but the trim() is not available on the number datatype.
To solve the “TypeError: trim is not a function”, make sure to call the trim() method on a data type string or convert the number to a string before calling the trim() method on it.
Here is an example:
const str = ' Welcome ';
const result = str.trim();
console.log(result);
Output:
'Welcome'
In the above example, we have used the trim() method on a valid string, so it removes the leading and trailing spaces of that string.
Note: The ‘trim()’ method creates a new string with the values that passes the test condition.
Type checking
To avoid the run time errors, we can also check the given datatype is a string or not before calling the trim() method on it.
Here is an example:
const value = 8999;
if(typeof value === 'string'){
console.log(value.trim(0,2));
}else{
console.log('Given value is not a string');
}
Conclusion
The “trim is not a function” error occurs, when we call a trim() method on a value which is not a string. To solve the error, convert the value to an string before calling the trim() method on it or make sure to use the trim() method on a valid strings.