How to Trim Space in Textbox using Javascript

In this tutorial, you will learn how to trim space in textbox using javascript. It is common to have an extra space at the end or at the beginning of a string present in the textbox. For a newbie developer, it can be a bit tricky to trim a space in the textbox.

There are numerous ways to trim a space in the textbox. But for the sake of simplicity, we will use trim() method. The trim() method removes any extra space at the beginning and at the end of a string.

In the following example, we will enter some random text in the input element and upon click of a button, we will trim the  space in the textbox and display the result on the screen.  Please have a look over the code example and the steps given below.

HTML & CSS

  • We have 3 elements in the HTML file (div, input, and button). The div element is just a wrapper for the rest of the elements.
  • The innerText for the button element is “Trim”.
  • We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
  • 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">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    
    <div>
        <input type="text">
        <button>Trim</button>        
    </div>
    <script src="script.js"></script>
</body>
</html>
body {
    text-align: center;
}

input, button {
    display: inline-block;
    padding: 10px 20px;
}

div {
    display: inline-block;
}

Javascript

  • We have selected the button element and input element using the document.querySelector() method and stored them in btnTrim and input variables respectively.
  • We have attached a click event listener to the button element.
  • In the event handler function, we are getting value from the textbox using value property and calling the trim() method to remove any space in the string. We are storing the returned value in the str variable.
  • We are setting str as value of the textbox.
let btnTrim = document.querySelector("button");
let input = document.querySelector("input");

btnTrim.addEventListener("click", () => {
  let str = input.value.trim();
  input.value = str;
});