Skip to main content
Regexflux

Leading/Trailing Whitespace

beginner

Matches leading and trailing whitespace for trimming.

whitespacetrimcleanupformatting

Pattern

/^\s+|\s+$/gm

Try It

0 of 5 strings matched

Explanation

Matches whitespace (spaces, tabs, etc.) at the start or end of each line. Useful for trim operations with regex replace.

Test Strings

Matching

  • leading spaces
  • trailing spaces
  • tab indented

Non-matching

  • no-whitespace
  • internal spaces only

Language Compatibility

LanguageSupport
JSFull support
PYTHONFull support
JAVAFull support
PHPFull support
GOFull support

Code Snippets

const regex = /^\s+|\s+$/gm;
const text = "your text here";
const matches = text.match(regex);
console.log(matches);

Related Patterns