April 30, 2022
How to Trim Input Value in Javascript
In this tutorial, you will learn how to trim input value in javascript. Trimming input value simply means removing any extra space at the beginning as well as at the end from the value present in the input element. For a newbie developer, it can be a bit tricky to trim an input value.
There are numerous ways to trim an input value. 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 input value 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 input element using
value
property and calling thetrim()
method. We are storing the returned value in thestr
variable. - We are setting
str
as value of the input element.
let btnTrim = document.querySelector("button"); let input = document.querySelector("input"); btnTrim.addEventListener("click", () => { let str = input.value.trim(); input.value = str; });