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 Pattern | Name / Component | Function & Rule |
|---|---|---|
| ^\s+ | Leading Whitespace | Matches whitespace at string start. |
| | | Or | Alternation operator. |
| \s+$ | Trailing Whitespace | Matches whitespace at string end. |
Frequently Asked Questions
Is this equivalent to String.prototype.trim()?
Related Regular Expressions
Browse All 40 PatternsData & Formatting
Duplicate Consecutive Words
Finds repeated words separated by whitespace like 'the the' or 'is is' using backreferences.
/\b(\w+)\s+\1\b/giTest regex
Data & Formatting
CSV Comma-Separated Line Parser
Splits a CSV line into fields respecting quotes around fields with embedded commas.
/(?:^|,)(?:"([^"]*(?:""[^"]*)*)"|([^,"]*))/gTest regex
Data & Formatting
URL Slug Matcher
Matches lowercase alphanumeric strings separated by single hyphens, ideal for SEO permalinks.
/^[a-z0-9]+(?:-[a-z0-9]+)*$/Test regex