How to Trim Every Element in Array in Javascript

In this tutorial, you will learn how to trim every element in array in javascript. Array is a collection of values and these values can be of same data type or not. Mostly, we have strings in a collection and these strings can have unwanted leading and trailing spaces. From a developer perspective, it can be a bit tricky to trim every element in array.

There are numerous ways to trim every element 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 every element 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 and ul).
  • 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 a script 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 our ul element.
  • In showUsers() method, we are simply looping through the users array and creating a template string with a bunch of li elements.
  • We are displaying that list in the ul element.
  • We have selected the button element using the document.querySelector() method and attached a click event listener to it.
  • In the event handler function, we are using map() method and calling trim() method of every element to remove any leading or trailing spaces.
  • Finally, we are calling showUsers() method to update the list of the users.
let users = ['  Marks   ', '   Jane   ', '  Tron   ', '   Gale   '];

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();
});