Removing blank lines from text using regex
A practical regular expression for removing extra blank lines from text, with C#, JavaScript and Python usage notes.
Removing surplus blank lines is a routine need when handling user-supplied content. Below are the C# and JavaScript versions of the same regular expression, plus a live example you can try.
The expression replaces the whitespace run before a line break with a single line break. The whitespace class includes tabs and carriage returns, so it works with both Windows and Unix line endings.
In JavaScript, do not forget the global (g) flag — without it only the first match changes. In C#, Replace already replaces every match.
C#
string text="....";
Regex r = new("\s+\n");
text = r.Replace(text, "\n");
Javascript
var text="....";
var r = /\s+\n/g;
text = text.replace(r, "\n");
Python
import re
text = "...."
r = re.compile(r'\s+\n')
text = r.sub("\n", text)
Short guide
When to use it
Blank lines often appear in text editors, contact forms, product descriptions and long user input. Cleaning repeated blanks before saving keeps the content easier to read without forcing the user to edit every line manually.
What to watch
- Test both Windows and Unix line endings; do not rely only on the output from your own machine.
- Do not remove paragraph spacing that the user intentionally added.
- Try to keep frontend and server-side cleanup rules consistent.
Common mistake
Removing every blank character can make the text flat and hard to read. The goal is not to delete all spacing, but to reduce uncontrolled repetition.
Before using this in a project
Regex examples are useful shortcuts, but real projects should also consider the data source, line endings, browser/server differences and user input mistakes. In web forms, admin panels and custom software, validation should not live only on the frontend; the server side should check it too.