Skip to main content
Data & Formatting · In-Browser Regular Expression Lab

Whitespace Trim Regex — Strip Leading and Trailing Whitespace

Matches beginning and ending spaces, tabs, and newlines for string sanitization.

Flags:
//g
Match Found
Load Sample:
Match Inspection & Details1 match
Match #1:

Test Samples Verification Matrix

Expected Valid Samples (Should Match)

leading spaces Pass
trailing spaces Pass
both ends Pass

Expected Invalid Samples (Must Reject)

no_spaces Rejected (Pass)
clean text with internal space Rejected (Pass)
Code Implementation Generator
// JavaScript / TypeScript (ES6+)
const pattern = /^\s+|\s+$/g;
const text = "  leading spaces";

const isMatch = pattern.test(text);
console.log("Is Match:", isMatch);

if (isMatch) {
  const matches = text.match(pattern);
  console.log("Matches:", matches);
}

Regular Expression Token Breakdown

Replaces leading `^\s+` or trailing `\s+$` characters with an empty string. Each component of the regular expression serves a distinct syntactical purpose as mapped below:

Token PatternName / ComponentFunction & Rule
^\s+Leading WhitespaceMatches whitespace at string start.
|OrAlternation operator.
\s+$Trailing WhitespaceMatches whitespace at string end.

Frequently Asked Questions

Is this equivalent to String.prototype.trim()?
Yes, replacing this pattern with an empty string replicates trim().
Browse All 40 Patterns