Last updated: Mar 3, 2024
Reading timeยท2 min
The "TypeError: trim is not a function" error occurs when we call the trim()
method on a value that is not a string.
To solve the error, convert the value to a string using the toString()
method or make sure to only call the trim
method on strings.
Here is an example of how the error occurs.
const arr = [' hey ', ' there ']; // โ๏ธ TypeError: trim is not a function arr.trim();
We called the String.trim() method on an array, which caused the error.
trim()
method on stringsTo solve the error, make sure to only call the trim() method on strings.
const str = ' hello '; const result = str.trim(); console.log(result); // ๐๏ธ "hello"
The trim()
method removes the leading and trailing whitespace from the string.
trim()
Alternatively, you can check if the value is a string before calling the
trim()
method.
const str = null; const result = typeof str === 'string' ? str.trim() : ''; console.log(result); // ๐๏ธ ""
We used the ternary operator to
check if the str
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.
You can also use a simple if
statement to achieve the same result.
const str = null; let result = ''; if (typeof str === 'string') { result = str.trim(); } console.log(result); // ๐๏ธ ""
trim
method, otherwise, we return an empty string for consistency.trim()
method on all strings in an ArrayIf you want to trim all strings in an array, use the Array.map()
method to
iterate over the array and call the trim()
method on each string.
const arr = [' bobby ', ' hadz ', ' com ']; const result = arr.map(str => str.trim()); // ๐๏ธ [ 'bobby', 'hadz', 'com' ] console.log(result);
The function we passed to the Array.map() method gets called with each element in the array.
On each iteration, we call the String.trim()
method on the current element and
return the result.
The map()
method returns a new array containing the values returned from the
callback function.
If the error persists, console.log
the value you're calling the trim
method
on and check its type using the typeof
operator.
console.log(typeof 'bobbyhadz.com'); // ๐๏ธ string console.log(typeof null); // ๐๏ธ object console.log(typeof {}); // ๐๏ธ object
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 trim()
method.
// โ with Objects const obj = { site: ' bobbyhadz.com ', }; const result1 = obj.site.trim(); console.log(result1); // ๐๏ธ "bobbyhadz.com" // ------------------------------------------- // โ with Arrays const arr = [' bobby ', ' hadz ', ' com ']; const result2 = arr[0].trim(); console.log(result2); // ๐๏ธ "bobby"
We accessed a property in the object and an element in the array before calling
the String.trim()
method.