Start free · Free tools · Fair usage limits
Browse Tools

Categories

Custom AI Solutions – AI2Flows
LIVE NEWS
Loading latest AI & SEO news…
Home›Tools›Regex Tester›Regex: Leading and trailing whitespace
Regex pattern · find & extract

Regex: Leading and trailing whitespace

Regex to trim whitespace: a tested pattern with examples, a plain-English breakdown, and code for JavaScript, Python, PHP, Java and Go.

Quick answer

Use /^\s+|\s+$/g with the global flag to find every match. In " hello world " it finds " ", " ". Most languages have a built-in trim (String.prototype.trim, Python’s str.strip) that is clearer and faster.

Last updated · Maintained by FreeAIToolz · How we test

/^\s+|\s+$/g

1 match(es)

hello world no-spaces
Open in the full Regex Tester (replace, flags, groups) →

How this regex works

PartMeaning
^\s+whitespace at the start
|or
\s+$whitespace at the end

Flags: g finds every match instead of stopping at the first.

Examples

InputMatches
hello world ,
no-spacesnone

Every example above is checked automatically in JavaScript and Python each time the site is built.

Limitations and edge cases

Most languages have a built-in trim (String.prototype.trim, Python’s str.strip) that is clearer and faster. The regex is useful in editors and tools that only offer find-and-replace.

When to use this pattern

Replace matches with an empty string to trim, e.g. text.replace(/^\s+|\s+$/g, "").

Use it in your language

JavaScript

const matches = text.match(/^\s+|\s+$/g) ?? [];

Python

import re
matches = [m.group(0) for m in re.finditer(r'^\s+|\s+$', text)]

PHP

preg_match_all('~^\\s+|\\s+$~', $text, $m);
$matches = $m[0];

Java

Matcher m = Pattern.compile("^\\s+|\\s+$").matcher(text);
while (m.find()) { System.out.println(m.group()); }

Go

re := regexp.MustCompile(`^\s+|\s+$`)
matches := re.FindAllString(text, -1)

More regex patterns

Frequently asked questions

What is the regex for Leading and trailing whitespace?
/^\s+|\s+$/g. Most languages have a built-in trim (String.prototype.trim, Python’s str.strip) that is clearer and faster. The regex is useful in editors and tools that only offer find-and-replace.
Which languages does this pattern work in?
It is tested in JavaScript and Python and uses syntax that also works in PHP (PCRE) and Java. It also works in Go’s RE2 engine.
How do I replace the matches?
In JavaScript use text.replace(/^\s+|\s+$/g, "replacement"); in Python use re.sub(r'^\s+|\s+$', "replacement", text).