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:
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
| Pattern | What it matches | Example use |
|---|---|---|
\s | One whitespace character | Does the string contain whitespace? |
\s+ | One or more whitespace characters in a row | Collapse runs of spaces into one |
\S | One character that is not whitespace | \S+ extracts words |
" " (a literal space) | Only the space bar character | Split on single spaces |
[ \t]+ | Spaces and tabs, not line breaks | Clean a line and keep the lines |
\r?\n | A line break on Windows or Unix | Split text into lines |
^\s+ and \s+$ | Whitespace at the start or at the end | Together they rebuild trim() |
\s{2,} | Two or more whitespace characters | Find double spaces |
^\S+$ | A string with no whitespace at all | Validate 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:
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 countsimport re
def has_whitespace(text):
return re.search(r"\s", text) is not None
print(has_whitespace("4Geeks Academy")) # True
print(has_whitespace("4GeeksAcademy")) # FalseTo check a URL before you use it, the same pattern catches the space that breaks it:
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:
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()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 regexWithout 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:
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'].
