April 30, 2022
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
, andbutton
). Thediv
element is just a wrapper for the rest of the elements. - The
innerText
for thebutton
element is“Trim”
. - We have done some basic styling using CSS and added the link to our
style.css
stylesheet inside thehead
element. - 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"> <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 andinput
element using thedocument.querySelector()
method and stored them inbtnTrim
andinput
variables respectively. - We have attached a
click
event listener to thebutton
element. - In the event handler function, we are getting value from the textbox using
value
property and calling thetrim()
method to remove any space in the string. We are storing the returned value in thestr
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; });