TypeError: trim is not a function in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

TypeError: trim is not a function in JavaScript #

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 using the toString() method or make sure to only call the trim method on strings.

typeerror trim is not a function

Here is an example of how the error occurs.

index.js
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.

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 toString() method.

index.js
const str = ' hello '; const result = str.trim(); console.log(result); // 👉️ "hello"

Alternatively, you can check if the value is a string before calling the trim() method.

index.js
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.

If the value is a string, we return the result of calling the trim method, otherwise we return an empty string for consistency.

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.

index.js
const arr = [' hey ', ' there ']; const result = arr.map(str => str.trim()); // 👇️ ['hey', 'there'] console.log(result);
The map method takes a function and calls it with each element in the array. On each iteration, we call the trim method to trim the whitespace from the beginning and end of the string.

If the error persists, console.log the value you're calling the trim method on and check its type using the typeof operator.

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.

Conclusion #

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 using the toString() method or make sure to only call the trim method on strings.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.