# Trim all strings in an array using JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Sep 11, 2022, updated Jun 10, 2023. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-trim-all-strings-in-array

> Learn how to use the map() and trim() methods to trim all strings in an array using JavaScript.

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()`](https://attacomsian.com/blog/javascript-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.

```javascript
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:

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

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

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