To remove leading and trailing whitespace from all strings in an array using JavaScript:

  1. Iterate over each element in the array using the Array.map() method.
  2. Apply the trim() method to each string in the iteration to remove the whitespace from both ends.
  3. The map() method will return a new array containing the updated strings with no whitespace.
const arr = [' zero ', ' one ', ' two ']

const updated = arr.map(item => item.trim())

console.log(updated)
// Output: [ 'zero', 'one', 'two' ]

The Array.map() method executes the provided callback function for every element in the array, creating a new array with the results. It doesn't modify the original array.

The trim() function eliminates leading and trailing whitespace from a string. It doesn't modify the original string either.

If you prefer to modify the original array directly, rather than creating a new one, you can use the Array.forEach() method:

const arr = [' zero ', ' one ', ' two ']

arr.forEach((item, index) => {
  arr[index] = item.trim()
})

console.log(arr)
// Output: [ 'zero', 'one', 'two' ]

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.