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, 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>
        <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 and textarea 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 textarea using value property and calling the trim() method. We are storing the returned value in the str 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;
});