Regex to Trim Trailing Whitespace from Lines
Regex to remove trailing whitespace from each line of a text file. Useful for code linting, diff hygiene, and cleaning up exported CSVs.
Detailed Explanation
Trim Trailing Whitespace
Trailing whitespace pollutes diffs and breaks some parsers. Most editors strip it on save, but regex is useful for batch cleanup or one-off scripts.
Trim Trailing Whitespace from Every Line
str.replace(/[ \t]+$/gm, "")
The m flag makes $ match at every line ending. The character class [ \t] covers spaces and tabs without touching the line terminator itself.
Trim Both Ends of Each Line
str.replace(/^[ \t]+|[ \t]+$/gm, "")
Trim Only the Whole String (not per-line)
str.replace(/^\s+|\s+$/g, "")
This is equivalent to String.prototype.trim().
Trim Only Leading or Only Trailing
str.replace(/^\s+/, "") // trimStart
str.replace(/\s+$/, "") // trimEnd
Tested Examples
| Input | Per-Line Trailing Trim |
|---|---|
"hello " |
"hello" |
"line1 \nline2\t\t" |
"line1\nline2" |
" preserved\n also preserved" |
unchanged (only trailing) |
"\t\n" |
"\n" |
Remove Trailing Newlines from a File
str.replace(/[\r\n]+$/, "\n")
Keeps a single final newline (POSIX convention).
Remove Empty Lines
str.replace(/^\s*\n/gm, "")
Practical Recommendation
Pair this regex with a pre-commit hook to keep your diffs clean. Many editors (VSCode, Vim, Sublime) have a one-click "Trim Trailing Whitespace" command. For mass cleanup of an existing repository, run:
find . -name "*.js" -exec sed -i "" -E "s/[[:space:]]+$//" {} +
(macOS sed syntax shown; GNU sed omits the empty quote argument.)
Why It Matters
Trailing whitespace causes:
- Spurious diffs in code review
- "Trailing whitespace" warnings in linters (ESLint, RuboCop)
- Hidden bugs in shell scripts where a trailing space changes argument parsing
Use Case
Cleaning trailing whitespace from a legacy codebase before adopting a strict linter, sanitizing CSV exports that have padding spaces in cells, or normalizing SQL files generated by GUI tools.