Regex to Match Trailing Whitespace

Detect trailing whitespace at the end of lines including spaces and tabs but not the newline itself. Useful for code cleanup and linting. Free online regex tester.

Regular Expression

/[^\S\n]+$/gm

Token Breakdown

TokenDescription
[^\S\n]Negated character class — matches any character NOT in \S\n
+Matches the preceding element one or more times (greedy)
$Anchors at the end of the string (or line in multiline mode)

Detailed Explanation

This regex detects trailing whitespace at the end of lines, a common code quality issue. Here is the token-by-token breakdown:

[^\S\n]+ — A negated character class with a double negation that effectively matches whitespace characters excluding newlines. Breaking it down: \S matches any non-whitespace character, and \n matches a newline. The negation [^...] inverts this, so the class matches characters that are NOT non-whitespace and NOT newlines. In other words, it matches whitespace characters that are not newlines: spaces, tabs, and other horizontal whitespace. The + quantifier requires one or more such characters.

$ — Anchors the match at the end of a line. With the m (multiline) flag, this matches at the end of each line rather than only at the end of the entire string.

The g flag enables global matching to find trailing whitespace on all lines, and the m flag enables multiline mode so $ matches at each line ending.

Trailing whitespace is considered undesirable in source code for several reasons: it creates unnecessary diffs in version control, it can cause issues in some programming languages and markup formats, it wastes bytes, and it is a common linting rule violation. Most code editors can be configured to automatically strip trailing whitespace on save.

This pattern is useful in code linters, pre-commit hooks, text editors, and CI/CD pipelines that enforce code style rules. It detects trailing spaces and tabs without matching the newline character itself, making it ideal for search-and-replace operations where you want to remove the whitespace but keep the line structure intact.

Example Test Strings

InputExpected
hello Match
text Match
no trailingNo Match
leading onlyNo Match
end space Match

Try It — Interactive Tester

//gm
gimsuy

Match Highlighting(3 matches)

hello text no trailing leading only end space

Matches & Capture Groups

#1 index 5
#2 index 13
#3 index 52
Pattern: 9 charsFlags: gmMatches: 3

Ctrl+Shift+C to copy regex

Customize this pattern →