Trim all Strings in an Array using JavaScript

avatar

Borislav Hadzhiev

Thu Oct 14 20211 min read

banner

Photo by Eric Nopanen

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 call the String.trim method on each string and then return it.

The map method does not 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);

In the code snippet we check if the current element is of type string before calling the trim() method.

We return elements of other types straight away, so they also get added to the new array.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee