Regex to trim whitespace

A regular expression that removes whitespace from both ends of a string, variants that collapse inner spaces or trim every line, and the Unicode spaces that each language counts differently.

//

Matches

This tool runs in your browser. We never send what you type or paste to a server.

The pattern

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

The two alternatives remove a run of whitespace at the start and a run at the end, and leave everything in between alone. The tester above runs it with the m flag so that you can see it work on each line; the code below works on a whole string.

The tester at the top of this page is loaded with this pattern and the example text. Edit either box to try your own.

How it works, token by token

PartMeaning
^At the start of the string…
\s+…one or more whitespace characters: spaces, tabs, line breaks and, in Unicode-aware engines, other space characters.
|Or
\s+one or more whitespace characters…
$…at the end of the string. The g flag makes JavaScript replace both ends, not just the first match.

What it does

InputOutput
␣ hello world ␣hello world
\thello\nhello
no changeno change
␣ ␣(empty string)
\u00a0nbsp\u00a0nbsp

Use the built-in trim when there is one

Every language has a trim function, and it is clearer and faster than a regex: str.trim() in JavaScript, str.strip() in Python, trim() in PHP and String.Trim() in C#. Reach for the pattern when you are already working with regexes, for example inside a larger replacement, or when you need one of the variants below. Be aware that the built-ins do not agree on what whitespace is. PHP's trim() by default removes only spaces, tabs, line breaks, carriage returns, NUL and vertical tabs (see the PHP manual), so a non-breaking space pasted from a web page survives it.

What \s matches in each language

Non-breaking spaces (U+00A0) arrive constantly in text copied from web pages and word processors, and a byte order mark (U+FEFF) sometimes sits at the start of a file. Whether \s removes them depends on the language:

console.log(/\s/.test('\u00a0'), /\s/.test('\ufeff'));  // → true true
console.log(JSON.stringify('\u00a0\ufeff hi \n'.trim()));  // → "hi"
print(bool(re.search(r'\s', '\u00a0')), bool(re.search(r'\s', '\ufeff')))  # → True False
print(repr('\u00a0\ufeff hi \n'.strip()))  # → '\ufeff hi'
Console.WriteLine(System.Text.RegularExpressions.Regex.IsMatch("\u00a0", @"\s") + " " + System.Text.RegularExpressions.Regex.IsMatch("\ufeff", @"\s"));  // → True False

All three treat the non-breaking space as whitespace, but only JavaScript treats the byte order mark as whitespace, in both \s and trim(). In Python or C#, remove a leading U+FEFF explicitly, or open files with an encoding that strips it, such as Python's utf-8-sig.

Collapsing spaces and trimming lines

To turn every run of whitespace, including line breaks, into a single space, replace \s+ with one space and then trim:

/\s+/g
InputOutput
a b\t\tca b c
line one\nline twoline one line two

To trim each line of a multi-line string but keep the line breaks, use [ \t] instead of \s, so the pattern cannot eat the line breaks themselves, and the m flag so ^ and $ apply to each line:

/^[ \t]+|[ \t]+$/gm
InputOutput
␣ a \n b ␣a\nb

On long input, prefer the built-in trim for the end of the string. With a backtracking engine, \s+$ on a long run of spaces followed by something else tries the run from every starting position, so the work grows with the square of its length. Inputs of a few kilobytes are fine; untrusted megabytes are not.

In JavaScript, Python, PHP and C#

JavaScript

const re = /^\s+|\s+$/g;
console.log('[' + '  hello world  '.replace(re, '') + ']'); // → [hello world]
console.log('[' + '\thello\n'.replace(re, '') + ']'); // → [hello]
console.log('[' + 'no change'.replace(re, '') + ']'); // → [no change]

Python

import re

pattern = re.compile(r'^\s+|\s+$')
print('[' + pattern.sub('', '  hello world  ') + ']')  # → [hello world]
print('[' + pattern.sub('', '\thello\n') + ']')  # → [hello]
print('[' + pattern.sub('', 'no change') + ']')  # → [no change]

PHP

<?php
$pattern = '/^\s+|\s+$/';
echo '[', preg_replace($pattern, '', '  hello world  '), "]\n"; // → [hello world]
echo '[', preg_replace($pattern, '', "\thello\n"), "]\n"; // → [hello]
echo '[', preg_replace($pattern, '', 'no change'), "]\n"; // → [no change]

C#

using System;
using System.Text.RegularExpressions;

var pattern = new Regex(@"^\s+|\s+$");
Console.WriteLine("[" + pattern.Replace("  hello world  ", "") + "]"); // → [hello world]
Console.WriteLine("[" + pattern.Replace("\thello\n", "") + "]"); // → [hello]
Console.WriteLine("[" + pattern.Replace("no change", "") + "]"); // → [no change]

JavaScript replaces only the first match unless the pattern has the g flag. Python's re.sub, PHP's preg_replace and .NET's Regex.Replace replace every match by default. The square brackets in the output are only there to show where the result starts and ends.

The JavaScript, Python and C# examples are run before each update and their output is compared with the comments. PHP is not installed on our build machine, so the PHP version is checked against the PCRE pattern modifier documentation, and its string literal is checked to hand PHP exactly the pattern tested here.

Questions

What is the regex to remove leading and trailing spaces?

^\s+|\s+$, replaced with an empty string. In JavaScript add the g flag so that both ends are replaced; Python's re.sub, PHP's preg_replace and C#'s Regex.Replace replace every match by default.

How do I replace multiple spaces with one?

Replace \s+ with a single space to also fold tabs and line breaks, or {2,} (a space followed by {2,}) to fold only runs of ordinary spaces.

Why does trim not remove a space at the start of my text?

It is probably a non-breaking space or a byte order mark. Python's strip and PHP's trim treat them differently from JavaScript; see the comparison on this page.