RegexRef Logo
✂️

Regex for Trim Whitespace

Matches leading and trailing whitespace to trim it.

Understanding The Regex Pattern

/^\s+|\s+$/g
Test in Visualizer ↗
Matches
  • test
  • \tword
  • end\n
Non-Matches
  • no-whitespace
  • middle whitespace

How this Pattern Works

Trimming whitespace is a fundamental text processing operation used to clean up user input before it is stored in a database or evaluated by application logic. This regex specifically targets trailing spaces, leading spaces, tabs, and line breaks at the absolute beginning or end of a string. Implementing this pattern helps prevent subtle bugs caused by invisible characters, ensures accurate string comparisons, and keeps databases clean from unnecessary blank spacing.

Implement The Regex In Your Code

javascript
const regex = /^\s+|\s+$/g;
'  test  '.replace(regex, '');
python
import re
regex = re.compile(r'^\s+|\s+$')
clean = regex.sub('', '  test  ')
go
import "regexp"
re := regexp.MustCompile(`^\s+|\s+$`)
clean := re.ReplaceAllString(`  test  `, "")
rust
use regex::Regex;
let re = Regex::new(r"^\s+|\s+$").unwrap();
let clean = re.replace_all("  test  ", "");