How to Trim Textarea in Javascript
In this tutorial, you will learn how to trim textarea in javascript. Textarea element is generally used for multiline text content. Trimming textarea simply means removing any extra space at the beginning as well as at the end from the value present in the textarea. For a newbie developer, it can be a bit tricky to trim a textarea.
There are numerous ways to trim a textarea. 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 textarea element and upon click of a button, we will trim the textarea 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
,textarea
, 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> <textarea name="" id="" cols="30" rows="10"></textarea> <button>Trim</button> </div> <script src="script.js"></script> </body> </html>
body { text-align: center; } textarea, button { display: block; margin-top: 5px; width: 100%; } div { display: inline-block; }
Javascript
- We have selected the
button
element andtextarea
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 textarea using
value
property and calling thetrim()
method. We are storing the returned value in thestr
variable. - We are setting
str
as value of the textarea.
let btnTrim = document.querySelector("button"); let input = document.querySelector("textarea"); btnTrim.addEventListener("click", () => { let str = input.value.trim(); input.value = str; });