JavaScript RegExp Whitespace Metacharacter (\s)

Beginner
6 min read
Updated: Oct 2026
3 examples
Live preview

What Is \s?

\s matches one whitespace character: space, tab, newline, and related separators. Use it to detect gaps, split words, or normalize messy spacing.

Remember
\s  → one whitespace (space, \t, \n, \r, \f, \v, …)
\S  → one non-whitespace (inverse)

/\s/.test("hello")        → false
/\s/.test("hello world")  → true
"a  b".replace(/\s+/g, " ") → "a b"
UsePrefer
Detect whitespace/\s/
Split into wordsstr.split(/\s+/)
Collapse gapsstr.replace(/\s+/g, " ")
Opposite class\S

How to Use \s

Match separators once, or use + when a whole run of whitespace matters.

  1. Start with /\s/ to ask “is there any whitespace?”
  2. Add + for runs: /\s+/ matches one or more separators.
  3. Use split(/\s+/) to break text into words.
  4. Use replace(/\s+/g, " ") to normalize spacing.
PieceRequired?Role
\s in the patternYesMatch one whitespace character
+ / *OptionalMatch a run (or optional run) of whitespace
g flagOptionalReplace every whitespace run
Inverse—\S matches non-whitespace

Pseudocode

Pseudocode
pattern has "\s"
read next character ch from the string

if ch is whitespace:   // space, tab, newline, …
    accept match
else:
    fail this path

common actions:
  test(str)                 → true if any whitespace exists
  split(/\s+/)              → words between whitespace runs
  replace(/\s+/g, " ")      → collapse runs to one space

Cheat Sheet

Keep these patterns handy for everyday text cleanup.

TopicDetail
One whitespace\s
Whitespace run\s+
Split wordssplit(/\s+/)
Collapse gapsreplace(/\s+/g, " ")
Trim edgesstr.trim() (or /^\s+|\s+$/g)
Opposite\S
StandardES3+ (universal)

Live Preview

Run common \s operations on sample strings with mixed whitespace.

Browser demo of the RegExp \s whitespace escape — same ideas as the examples below.

Result
text = "hello"
/\s/.test(text)
→ false

/* no whitespace present */

JavaScript Examples

Short, copy-ready snippets. Open DevTools Console, or use Try It Yourself for a live editor.

Example 1 — Detect Whitespace

Return true when space, tab, or newline appears anywhere in the text.

JavaScript
console.log(/\s/.test("hello"));       // false
console.log(/\s/.test("hello world")); // true
console.log(/\s/.test("a\tb"));        // true
Try It Yourself

How It Works

  1. Plain word. "hello" has no separators → false.
  2. Space matches. The gap in "hello world" is whitespace → true.
  3. Tab matches too. "\t" is also whitespace, not only the space bar.
  4. One character. Bare \s asks “is there any whitespace?” — not how many.

Example 2 — Split on Whitespace

Break mixed spaces and tabs into clean word tokens.

JavaScript
const text = "one   two\tthree";

console.log(text.split(/\s+/));
// ["one", "two", "three"]
Try It Yourself

How It Works

  1. Messy gaps. Words are separated by spaces and a tab.
  2. Use \s+. One or more whitespace characters form one delimiter.
  3. Split cuts there. Each run becomes a boundary between tokens.
  4. Clean result. You get three words — spacing style no longer matters.

Example 3 — Collapse Extra Spaces

Normalize runs of whitespace down to a single space.

JavaScript
const padded = "too    many     spaces";
const tabs = "hello\t\tworld";

console.log(padded.replace(/\s+/g, " ")); // "too many spaces"
console.log(tabs.replace(/\s+/g, " "));   // "hello world"
Try It Yourself

How It Works

  1. Find every run. The g flag walks the whole string.
  2. Match with \s+. Multiple spaces or tabs count as one run.
  3. Replace with one space. Each run becomes a single " ".
  4. Tabs normalize too. Horizontal tabs become regular spaces in the result.

Edge Cases & Pitfalls

Check these before relying on \s in real projects.

split

Leading or trailing \s+ creates empty tokens

" a b ".split(/\s+/) yields empty strings at the ends. Trim first, or filter empty entries.

literal

A literal space is narrower than \s

/ / matches only the space bar. Tabs and newlines need \s (or an explicit escape).

null

\s does not match NUL

The null character is not whitespace. Use \0 / \x00 when you need to find null bytes.

trim

Prefer trim() for simple edges

For leading/trailing cleanup alone, str.trim() is clearer than /^\s+|\s+$/g.

Browser & Runtime Support

The \s whitespace escape is core regex syntax (ES3+) and works everywhere JavaScript runs.

✓ Baseline · ES3+

RegExp \s

Supported in every modern and legacy browser, plus all Node.js versions. No polyfill required.

100% Universal support
Google Chrome Supported · Desktop & Mobile
Full support
Mozilla Firefox Supported · Desktop & Mobile
Full support
Apple Safari Supported · macOS & iOS
Full support
Microsoft Edge Supported · Chromium
Full support
Internet Explorer No native support · Use a polyfill
Polyfill
Opera Supported · Modern versions
Full support
Samsung Internet Supported · Android
Full support
Bun Supported · JavaScript runtime
Supported
Deno Supported · JavaScript runtime
Supported
Node.js Supported · Server runtime
Supported
Android WebView Supported · Modern WebView
Full support
\s Excellent

Bottom line: Safe to use in any JavaScript environment. Pair with \S when you need the non-whitespace side.

Performance Notes

ApproachCostBest for
/\s/.test(str)O(n)Quick “has whitespace?” checks
str.split(/\s+/)O(n)Tokenizing messy text
str.replace(/\s+/g, " ")O(n)Normalizing spacing

Character-class style matches are cheap. Prefer \S when you want the visible parts, and \s when you want the separators.

Key Takeaways

  • Role: \s matches one whitespace character (space, tab, newline, …).
  • Runs: use \s+ to match or replace whole gaps.
  • Split: split(/\s+/) turns mixed spacing into words.
  • Inverse: \S matches everything that is not whitespace.

One line: \s finds whitespace — detect it, split on \s+, or collapse runs with replace(/\s+/g, " ").

Frequently Asked Questions

\s matches any single whitespace character: space, tab (\t), newline (\n), carriage return (\r), form feed (\f), and vertical tab (\v). Modern engines also treat several Unicode separators as whitespace.
\s matches whitespace. \S is the inverse and matches any character that is not whitespace—letters, digits, and punctuation.
No. A literal space matches only the space character. \s matches space plus tab, newline, and other whitespace types.
Use split with a quantifier: str.split(/\s+/). Prefer trim() first if leading or trailing whitespace would create empty array entries.
No. The null character (\0, U+0000) is not whitespace in JavaScript.
The \s whitespace shorthand is core regex syntax since ES3. It works in every browser and Node.js version.

Next: \t tab

Learn how the tab metacharacter matches horizontal tab characters specifically.

\t tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful