T
ToolPrime

Regex for Whitespace Trim

Matches leading and trailing whitespace for trimming.

Pattern

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

Live Tester

Enter a string to test

Examples

The g flag makes the pattern apply special matching behavior and match globally.

hello
hello
hello
hello
no-whitespace

Pattern Breakdown

^\s+ — whitespace at start

| — or

\s+$ — whitespace at end

Code Snippets

Javascript

"  hello  ".replace(/^\s+|\s+$/g, ""); // "hello"

Python

import re
re.sub(r"^\s+|\s+$", "", "  hello  ")  # "hello"

Php

preg_replace('/^\s+|\s+$/', "", "  hello  "); // "hello"

Related Patterns

Frequently Asked Questions

What is the regex for Whitespace Trim?
The regex pattern for Whitespace Trim is /^\s+|\s+$/g. Matches leading and trailing whitespace for trimming.
How do I use the Whitespace Trim regex in JavaScript?
In JavaScript you create the pattern with a regex literal or the RegExp constructor and call .test() to check a string against it. A ready-to-copy example is shown in the Code Snippets section above, alongside Python and PHP versions.
What does the Whitespace Trim pattern match?
It matches strings like hello ; it rejects strings like hello. See the Examples section above for the full list of matching and non-matching cases.

Related Tools