4Geeks chosen to deliver AI education in the Bahamas alongside Harvard, Oxford, and Columbia.See more

RegEx for whitespaces

By 4Geeks

Find, remove and collapse spaces, tabs and line breaks with \s, \s+ and \S in JavaScript and Python.

8 min readLast updated
Regex whitespace icon

What is the regex for whitespace?

Short answer: \s matches one whitespace character: a space, a tab (\t), a line break (\n or \r), a vertical tab (\v) or a form feed (\f). \s+ matches one or more of them in a row, and \S matches any character that is not whitespace. In JavaScript, /\s+/g finds every run of spaces, tabs and line breaks in a string:

javascript
const text = "4Geeks   Academy\tMiami\nFlorida";
console.log(text.replace(/\s+/g, " ")); // "4Geeks Academy Miami Florida"

A literal space in a pattern, as in / /, matches only the space bar character. It does not match tabs or line breaks.

\s finds whitespace, \s+ groups it into runs and \S matches everything else. With these three you can check, clean and split almost any text.

Whitespace regex patterns at a glance

PatternWhat it matchesExample use
\sOne whitespace characterDoes the string contain whitespace?
\s+One or more whitespace characters in a rowCollapse runs of spaces into one
\SOne character that is not whitespace\S+ extracts words
" " (a literal space)Only the space bar characterSplit on single spaces
[ \t]+Spaces and tabs, not line breaksClean a line and keep the lines
\r?\nA line break on Windows or UnixSplit text into lines
^\s+ and \s+$Whitespace at the start or at the endTogether they rebuild trim()
\s{2,}Two or more whitespace charactersFind double spaces
^\S+$A string with no whitespace at allValidate usernames or slugs

Check if a string contains whitespace

test() returns true or false in JavaScript, and re.search() returns a match or None in Python:

javascript
const hasWhitespace = (str) => /\s/.test(str);
 
console.log(hasWhitespace("4Geeks Academy")); // true
console.log(hasWhitespace("4GeeksAcademy"));  // false
console.log(hasWhitespace("4Geeks\tAcademy")); // true, a tab counts
python
import re
 
def has_whitespace(text):
    return re.search(r"\s", text) is not None
 
print(has_whitespace("4Geeks Academy"))  # True
print(has_whitespace("4GeeksAcademy"))   # False

To check a URL before you use it, the same pattern catches the space that breaks it:

javascript
const url = "https://4geeks.com/how to";
if (/\s/.test(url)) {
  console.log("Whitespace found in the URL");
}

Replace or remove whitespace

Use replace() with the g flag in JavaScript, or re.sub() in Python, which replaces every match by default:

javascript
const messy = "  Learn   to\tcode \n with   AI  ";
 
console.log(messy.replace(/\s+/g, ""));        // "LearntocodewithAI"
console.log(messy.replace(/\s+/g, " ").trim()); // "Learn to code with AI"
console.log(messy.replace(/^\s+|\s+$/g, ""));   // same as messy.trim()
python
import re
 
messy = "  Learn   to\tcode \n with   AI  "
 
print(re.sub(r"\s+", "", messy))          # LearntocodewithAI
print(re.sub(r"\s+", " ", messy).strip())  # Learn to code with AI
print(" ".join(messy.split()))            # same result, without regex

Without the g flag, JavaScript only replaces the first match: "a b c".replace(/\s+/, "") returns "ab c".

Split a string on whitespace

Splitting on a single space leaves empty items when there are double spaces. Split on \s+ and trim first:

javascript
const line = "  red   green\tblue ";
 
console.log(line.split(" "));            // ["", "", "red", "", "", "green\tblue", ""]
console.log(line.trim().split(/\s+/));   // ["red", "green", "blue"]
console.log(line.match(/\S+/g));         // ["red", "green", "blue"]

In Python, split() with no arguments already splits on any run of whitespace and ignores the ends: " red green\tblue ".split() returns ['red', 'green', 'blue'].

Career · AI Engineering for Developers

You can clean any string, now build AI apps with it

Use the coding skills you already have to build AI agents, RAG systems and LLM-powered apps, with mentors and real projects.

Use whitespace regex with AI

An AI assistant such as ChatGPT, Claude or GitHub Copilot writes and explains regex quickly, but it can miss cases you did not mention. Give it real input, the output you expect and the language you use. These three prompts are ready to copy.

1. Write the pattern for your case

I need a regex in [JavaScript / Python] that [collapses repeated spaces / removes spaces but keeps line breaks / rejects usernames with whitespace].
Input: [paste 3 real examples]
Expected output: [paste what each one should become]
Explain each part of the pattern and give me the code.

2. Debug a pattern that does not match

This regex does not work as I expect in [language]:
[paste the line, e.g. new RegExp("\s+")]
Input: [paste the text]  Result: [paste what you got]
Explain why and give me the fix.

3. Test the edge cases

Write tests for this whitespace regex: [paste it]
Include tabs, Windows line breaks (\r\n), non-breaking spaces ( ), empty strings and leading and trailing spaces.

Run the answer against your own examples before you use it. Online testers such as regex101 show what each part of the pattern matches.

\s in JavaScript, Python and Java

\s means the same thing everywhere for spaces, tabs and line breaks, but each language writes it differently and treats Unicode spaces differently:

LanguageHow you write itNon-breaking space ( )
JavaScript/\s+/g or new RegExp("\\s+", "g")Matches
Pythonre.sub(r"\s+", " ", text)Matches in str patterns, not with re.ASCII
Javatext.replaceAll("\\s+", " ")Does not match unless you add (?U)

In JavaScript, \s also matches the byte order mark () that some files start with. Python's \s does not.

Match spaces and tabs but not line breaks

\s includes \n and \r, so /\s+/g joins all your lines into one. To clean each line and keep the line breaks, use a character class:

javascript
const text = "name:   Ana \t\nrole:\t\tdev";
 
console.log(text.replace(/[ \t]+/g, " "));
// "name: Ana \nrole: dev"

[^\S\r\n] is a stricter version: any whitespace except line breaks, including non-breaking spaces.

Remove non-breaking spaces from copied text

Text copied from web pages, PDFs or Word often contains non-breaking spaces ( ). They look like normal spaces, but " " does not match them. \s does, in JavaScript and in Python:

javascript
const copied = "Total: 250";
console.log(copied.split(" "));            // ["Total: 250"]
console.log(copied.replace(/\s/g, " "));   // "Total: 250"

The zero-width space (​) is not whitespace for regex, so remove it explicitly with /​/g.

Validate input with no whitespace

Anchor \S+ to the start and end of the string to reject any value that contains a space, a tab or a line break:

javascript
const isValidUsername = (name) => /^\S+$/.test(name);
 
console.log(isValidUsername("ana_dev"));  // true
console.log(isValidUsername("ana dev"));  // false
console.log(isValidUsername(""));         // false, + needs one character
python
import re
 
print(bool(re.fullmatch(r"\S+", "ana_dev")))  # True
print(bool(re.fullmatch(r"\S+", "ana dev")))  # False
Learn with a mentor

From regex patterns to shipping AI features

In the 4Geeks AI Engineering for Developers program you add AI agents, RAG and production LLM apps to your portfolio.

Common errors with whitespace regex

What you seeWhy it happensFix
new RegExp("\s+") matches the letter sIn a normal string, \s turns into s before the regex sees itWrite new RegExp("\\s+") or use the literal /\s+/
replace(/\s+/, "") only removes the first spaceThe pattern has no g flagUse /\s+/g
TypeError: String.prototype.replaceAll called with a non-global RegExp argumentreplaceAll() with a regex requires the g flagUse /\s/g
SyntaxWarning: invalid escape sequence '\s' in PythonThe pattern is not a raw stringWrite it as r"\s+"
split(" ") returns empty itemsDouble spaces leave empty strings between themUse trim().split(/\s+/) in JavaScript or split() in Python
test() alternates between true and falseA regex with the g flag remembers lastIndex between callsRemove g when you only use test()
replace(/\s*/g, "-") adds characters everywhere* also matches zero characters, so it matches between every letterUse + instead of *
Free download

Every whitespace pattern in a 2-page cheat sheet

The patterns you need, ready-to-copy recipes in JavaScript and Python, how \s changes between languages, the most common errors and prompts for ChatGPT, Claude or Copilot. Free, in PDF.

Regex for whitespace cheat sheet

2 pages · PDF · 4Geeks

  • 10 whitespace patterns and what each one matches
  • JavaScript and Python recipes side by side
  • The 6 most common errors and prompts to fix them with AI

Get it free

Your PDF right away

Frequently asked questions about regex for whitespace

Want to go from regex and string handling to building AI apps, with real projects and mentors?

See the AI Engineering for Developers program