How to Trim All Items in Array in Javascript
In this tutorial, you will learn how to trim all items in array in javascript. An array is a collection of values that can be of the same data type or not. Strings are commonly found in collections, and these strings may contain unwanted leading and trailing spaces. From a developer perspective, it can be a bit tricky to trim all items in array.
There are numerous ways to trim all items in array. But for the sake of simplicity, we will use map()
method and trim()
to accomplish our goal. The map()
method calls a certain function for each element and return a new array. The trim()
method will remove any leading or trailing spaces.
In the following example, we have one global array of strings. Upon click of a button, we will trim all items in array and display the result on the screen. Please have a look over the code example and the steps given below.
HTML & CSS
- We have 2 elements in the HTML file (
button
andul
). - The
innerText
for the button element is“Get”
. - The
ul
element is empty for now and we will populate it dynamically using javascript. - We have also included our javascript file
script.js
with ascript
tag at the bottom.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <button>Get</button> <ul></ul> <script src="script.js"></script> </body> </html>
Javascript
- We have a global variable
users
and it holds an array of strings. - We have the
showUsers()
method which is responsible for populating ourul
element. - In
showUsers()
method, we are simply looping through theusers
array and creating a template string with a bunch ofli
elements. - We are displaying that list in the
ul
element. - We have selected the
button
element using thedocument.querySelector()
method and attached aclick
event listener to it. - In the event handler function, we are using
map()
method and callingtrim()
method of each element to remove any leading or trailing spaces. - Finally, we are calling
showUsers()
method to update the list of theusers
.
let users = [' Game ', ' Fame ', ' Name ', ' Tame ']; function showUsers(){ let template = users.map(user => `<li>${user}</li>`).join('\n'); document.querySelector('ul').innerHTML = template; } showUsers(); document.querySelector('button').addEventListener('click', () => { users = users.map(item => item.trim()); showUsers(); });