How to Remove Blank Lines From Textarea using JavaScript?

Here is an example of a JavaScript function that can be used to remove blank lines from a textarea:

Remove Blank Lines from textarea Example

The below function takes a string of text as input and returns the same string with all the blank lines removed. It uses the regular expression /^\s*$/gm, which matches any line that contains only whitespace characters (spaces, tabs, newlines, etc.). The g flag indicates that the regular expression should search for matches globally (i.e. in the entire input string), and the m flag indicates that the regular expression should treat the input string as multiple lines. The replace method is used to replace all matches of the regular expression with an empty string, effectively removing the blank lines.

function removeBlankLines(text) { 
   return text.replace(/^\s*$/gm, ''); 


// Example usage: 
var textarea = document.getElementById('myTextarea');
textarea.value = removeBlankLines(textarea.value);


  1. Remove Element on Click using JavaScript
  2. Replace Null with 0 in JavaScript
  3. Convert NaN to 0 in JavaScript

Written by Vinish Kapoor

An Oracle Apex Consultant, Oracle ACE, and founder of and a question and answer forum for developers. You can connect with me on Facebook and Twitter.

Leave a Reply

Your email address will not be published. Required fields are marked *