Wed Oct 20 2021·2 min read
Photo by Johanneke Kroesbergen-Kamps
The "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
toString() method or make sure to only call the
trim method on
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 and got the error back.
To solve the error, make sure to only call the
trim() method on strings. You
can convert most values to a string by using the
const str = ' hello '; const result = str.trim(); console.log(result); // 👉️ "hello"
Alternatively, you can check if the value is a string before calling the
const str = null; const result = typeof str === 'string' ? str.trim() : ''; console.log(result); // 👉️ ""
We used a 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.
trimmethod on it, otherwise we return an empty string to be consistent.
If you want to trim all strings in an array, use the
map method to iterate
over the array and call the
trim method on each string.
const arr = [' hey ', ' there ']; const result = arr.map(str => str.trim()); // 👇️ ['hey', 'there'] console.log(result);
mapmethod takes a function and calls the function on each element in the array. On each iteration, we call the
trimmethod to trim the whitespace from the beginning and end of each string.
If the error persists,
console.log the value you're calling the
on and check it's type using the
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
I'll send you 1 email a week with links to all of the articles I've written that week