How to Trim all Strings in an Array using JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 2, 2024
4 min

banner

# Table of Contents

  1. Trim all Strings in an Array using JavaScript
  2. Checking if the element is a string before calling trim()
  3. Trim all Strings in an Array using forEach()
  4. Trim all Strings in a two-dimensional array
  5. Trim all Strings in an Array using a for loop

# Trim all Strings in an Array using JavaScript

To trim all strings in an array:

  1. Use the Array.map() method to iterate over the array.
  2. Call the String.trim() method on each string and return the result.
  3. The map() method will return a new array containing only strings with the whitespace from both ends removed.
index.js
const arr = [' bobby ', ' hadz ', ' com ']; const results = arr.map(element => { return element.trim(); }); console.log(results); // ๐Ÿ‘‰๏ธ [ 'bobby', 'hadz', 'com' ]

trim all strings in array

If you want to change the array in place, scroll down to the next subheading.

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 Array.map() method doesn't change the contents of the original array, it returns a new array.

If you have to do this often, define a reusable function.

index.js
function trimArray(array) { return array.map(element => element.trim()); } const arr = trimArray([' bobby ', ' hadz ', ' com ']); console.log(arr); // ๐Ÿ‘‰๏ธ [ 'bobby', 'hadz', 'com' ]

The trimArray function takes an array as a parameter and removes the leading and trailing whitespace from all strings in the array.

# Checking if the element is a string before calling trim()

If your array contains elements of other types, e.g. numbers or objects, add an if statement 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);

checking if element is string before calling trim

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

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

The Array.map() method doesn't change the array in place, it returns a new array.

If you want to change the array in place, use the Array.forEach() method.

# Trim all Strings in an Array using forEach()

This is a three-step process:

  1. Use the Array.forEach() method to iterate over the array.
  2. Use the String.trim() method to trim each string.
  3. Reassign the value of the array element to the output of the trim() method.
index.js
const arr = [' bobby ', ' hadz ', ' com ']; arr.forEach((element, index) => { arr[index] = element.trim(); }); console.log(arr); // ๐Ÿ‘‰๏ธ [ 'bobby', 'hadz', 'com' ]

trim all strings in array using foreach

The function we passed to the Array.forEach() method gets called with each element and index.

On each iteration, we update the value at the current index to the output of calling the trim() method with the element.

The Array.forEach() method changes the original array in place.

If your array might contain values of other types, use an if statement to check if the current value is a string before calling the String.trim() method.

index.js
const arr = [' bobby ', 2, ' hadz ', {}, ' com ']; arr.forEach((element, index) => { if (typeof element === 'string') { arr[index] = element.trim(); } }); console.log(arr); // ๐Ÿ‘‰๏ธ [ 'bobby', 2, 'hadz', {}, 'com' ]

We used the typeof operator to check if each element is a string before calling the String.trim() method.

If the array element isn't a string, it remains unchanged.

Which approach you pick is a matter of personal preference. I'd use the Array.map() method as I find it quite direct and easy to read.

# Trim all Strings in a two-dimensional array

If you need to trim all strings in a two-dimensional array, call Array.map() twice.

index.js
const arr = [ [' a ', ' b '], [' c ', ' d '], ]; const result = arr.map(subarray => subarray.map(str => str.trim()), ); console.log(result); // ๐Ÿ‘‰๏ธ [ [ 'a', 'b' ], [ 'c', 'd' ] ]

trim all strings in two dimensional array

We used the Array.map() twice in the example.

The first call to the map() method is used to iterate over the array and the nested calls to iterate over the subarrays.

On each iteration, we call the trim() method to remove the leading and trailing whitespace from the current string.

If you need to flatten the two-dimensional array and remove the leading and trailing whitespace, use the Array.flatMap() method instead.

index.js
const arr = [ [' a ', ' b '], [' c ', ' d '], ]; const result = arr.flatMap(subarray => subarray.map(str => str.trim()), ); console.log(result); // ๐Ÿ‘‰๏ธ [ 'a', 'b', 'c', 'd' ]

The Array.flatMap() method flattens the result that the map() method returns.

# Trim all Strings in an Array using a for loop

You can also use a basic for loop to trim all strings in an array.

index.js
const arr = [' bobby ', ' hadz ', ' com ']; for (let index = 0; index < arr.length; index++) { arr[index] = arr[index].trim(); } console.log(arr); // ๐Ÿ‘‰๏ธ [ 'bobby', 'hadz', 'com' ]

trim all strings in array using for loop

We used a for loop to iterate over the array of strings.

On each iteration, we access the array element at the current index and trim the string.

The syntax for a basic for loop is a bit verbose and in general the forEach() method should be preferred.

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.

Copyright ยฉ 2024 Borislav Hadzhiev