How to Remove Blank Lines From Textarea using JavaScript?

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, ''); 
}

Usage

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

Related:

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