Regex to trim whitespace

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

text.replace(/^\s+|\s+$/g, '') removes whitespace from both ends of a string and leaves the inside alone. The pattern has two alternatives: ^\s+ is the whitespace at the start, and \s+$ the whitespace at the end. The g flag matters: without it, replace() stops after the first match, and only the start gets trimmed.

In the tester below, Hello, world! with a tab at the end becomes Hello, world!: the three spaces in the middle stay.

Just use trim()

In JavaScript, text.trim() does exactly this, and it’s faster and clearer. It removes the same characters as \s: spaces, tabs, line breaks, the no-break space and the other Unicode spaces. trimStart() and trimEnd() do one side each. The regex earns its place where there’s no trim(), such as in a search-and-replace box, in a config file that takes a pattern, or in a chain of replacements.

Collapsing the inside too

To also squeeze every run of whitespace inside the string down to one space:

text.trim().replace(/\s+/g, ' ');   // "Hello, world!"

Trimming every line

With the m flag, ^ and $ match at every line, so it looks as if /^\s+|\s+$/gm trims each line. It does more than that: \s matches line breaks too, so it swallows blank lines and can join lines together.

'  a  \n\n  b  '.replace(/^\s+|\s+$/gm, '');         // "ab"
'  a  \n\n  b  '.replace(/^[^\S\r\n]+|[^\S\r\n]+$/gm, ''); // "a\n\nb"

[^\S\r\n] reads as “not a non-whitespace character, and not a line break”, which is whitespace other than line breaks. Use it whenever a pattern must stay on one line.

Other languages

The same pattern works almost everywhere, with one difference to watch: what \s covers. In JavaScript it includes the no-break space, U+00A0, which often arrives in text pasted from web pages. Java’s \s is ASCII-only unless you set the UNICODE_CHARACTER_CLASS flag, and Java’s trim() removes only characters up to U+0020, so both leave a no-break space in place.

Try it in the Regex Tester

Flags

$1 or $<name> for a group, $& for the whole match, $$ for a dollar sign. Leave it empty to delete the matches.

2 matches

After replace()

Hello,   world!

Matches

#MatchAtGroups
1 0–3none
2 18–21none

What the pattern means

  • ^\s+|\s+$Either of 2 alternatives, tried from left to right
    • ^\s+First alternative, in order
      • ^The start of the string
      • \s+A whitespace character (space, tab, line break or another Unicode space), one or more times, as many times as possible (greedy)
    • \s+$Second alternative, in order
      • \s+A whitespace character (space, tab, line break or another Unicode space), one or more times, as many times as possible (greedy)
      • $The end of the string
  • g global: Find every match, not just the first. exec() and test() carry on from lastIndex.

Runs in your browser. Nothing you enter is sent anywhere.