Trim all Strings in an Array using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Check out my new book

Trim all Strings in an Array using JavaScript #

To trim all strings in an array:

  1. Use the map() method to iterate over the array and call the trim() method on each array element.
  2. The map method will return a new array, containing only strings with the whitespace from both ends removed.
index.js
const arr = [' a ', ' b ', ' c ']; const results = arr.map(element => { return element.trim(); }); console.log(results); // 👉️ ['a', 'b', 'c']

The function we passed to the Array.map method gets called with each element in the array.

The map method returns a new array containing the values the callback function returned.

We called the String.trim method on each string and returned the result.

The trim() method removes the leading and trailing whitespace from a string.

index.js
console.log(' abc '.trim()); // 👉️ 'abc' console.log(' abc '.trim().length); // 👉️ 3
The map method doesn't change the contents of the original array, it returns a new array.

If your array contains elements of other types, e.g. numbers or objects, add an if condition to check if the current element is a string before calling the trim() method.

index.js
const arr = [' a ', 2, ' b ', {}]; const results = arr.map(element => { if (typeof element === 'string') { return element.trim(); } return element; }); // 👇️ ['a', 2, 'b', {}] console.log(results);

We check if the current element is of type string before calling the trim() method.

Elements of other types get returned straight away, so they also get added to the new array.

Further Reading #

Use the search field on my Home Page to filter through my more than 3,000 articles.