How To Trim All Strings In An Array Using JavaScript

Trim all Strings in an Array using JavaScript

This article will show you two common ways to trim all strings in an array using JavaScript: Using the map(), Array.forEach(), and trim() methods. Start reading the detailed article.

Trim all strings in an array using JavaScript

Using the map() and trim() method

In a first way, we will use the map() method to callback the function for each element in the array. Then call the trim() method to remove all whitespace from the element in myArray. The trim() method will clear whitespace from the strings.

Code example:

In this example, we call the trim() method to clear whitespace from each element in the array, and we call the map() method to iterate over the array. Let’s see the example below to get more information.

let myArray = [' Welcome ', ' to ', ' LearnShareIT  ']
console.log("My array is: ", myArray)

// Calling the trim() method to remove whitespace in element
let trimArray = myArray.map(element => element.trim())

console.log("After trimming all strings in my array: ", trimArray)

Output

My array is:  [ ' Welcome ', ' to ', ' LearnShareIT  ' ]
After trimming all strings in my array:  [ 'Welcome', 'to', 'LearnShareIT' ]

Using the Array.forEach() and trim() method

The next way is using the Array.forEach() method with trim() method to trim all whitespace of each element in the array.

  • We create the myArray with many whitespaces in each element.
  • After that, we used myArray.forEach() function to loop to all elements in myArray.
  • On each element, we call the trim() method to remove the whitespace of each element in the array.

Let’s see the example below to get more information:

let myArray = [' Welcome ', ' to ', ' LearnShareIT  ']
console.log("My array is: ", myArray)

// Use myArray.forEach() function to loop to all elements in myArray, 
// call the trim() method to remove the whitespace of each element in the array
myArray.forEach((element, index) => {
  	myArray[index] = element.trim()
})

console.log("After trim all strings in my array: ", myArray)

Output

My array is:  [ ' Welcome ', ' to ', ' LearnShareIT  ' ]
After trim all strings in my array:  [ 'Welcome', 'to', 'LearnShareIT' ]

Summary

Using the map() and the trim() method to trim all strings in an array using JavaScript will make it more convenient for you to remove all whitespaces of each element. What about your opinion? Leave your comment here to share with us. Thank you for your reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *