JavaScript RegExp \s Metacharacter

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Whitespace

What You’ll Learn

The \s metacharacter matches any single whitespace character: spaces, tabs, newlines, and related separators. It is one of the most practical regex tools for parsing text, normalizing spacing, and splitting words.

01

Whitespace

\s

02

Includes

Space, tab, LF

03

Inverse

\S

04

Quantifiers

\s+

05

Split

split(/\s+/)

06

Normalize

replace(/\s+/g, " ")

Introduction

Text from users, files, and APIs often contains inconsistent whitespace—multiple spaces, tabs, or line breaks. The \s metacharacter gives you a single shorthand to match all common separator types instead of listing each one manually.

One \s matches exactly one whitespace character. Add + to match runs of whitespace, or use split(/\s+/) to break text into words regardless of how it is spaced.

Understanding the \s Metacharacter

In JavaScript, \s is a predefined character class escape that matches these whitespace characters:

  • Space ()
  • Tab (\t)
  • Line feed / newline (\n)
  • Carriage return (\r)
  • Form feed (\f)
  • Vertical tab (\v)
JavaScript
/\s/.test("hello");       // false
/\s/.test("hello world"); // true  (space)
/\s/.test("a\tb");         // true  (tab)

"one  two".match(/\s+/);   // ["  "]

The uppercase form \S matches everything that is not whitespace—letters, digits, and punctuation.

💡
Beginner Tip

To split messy input into words, write text.split(/\s+/). It handles spaces, tabs, and newlines in one pattern.

How to Use \s in JavaScript

Use \s in detection, splitting, normalization, and trimming workflows:

JavaScript
/\s/.test("hello");                 // false
"one  two  three".split(/\s+/);     // ["one", "two", "three"]
"too   many".replace(/\s+/g, " "); // "too many"
"  hi  ".replace(/^\s+|\s+$/g, ""); // "hi"

Pair \s with anchors (^, $), quantifiers (+, *), and the global flag for bulk replacement.

📝 Syntax

JavaScript
\s              // one whitespace character
\s+             // one or more whitespace chars
\s*             // zero or more whitespace chars
/\s/g           // global: every whitespace char
\S              // one non-whitespace (inverse)

Common patterns

  • /\s+/ — match a run of whitespace (gap between words).
  • split(/\s+/) — split text on any whitespace delimiter.
  • /\s+/g with replace(" ", ...) — collapse multiple spaces.
  • /^\s+|\s+$/g — trim leading and trailing whitespace.

⚡ Quick Reference

GoalPattern
One whitespace\s
Whitespace run\s+
Split into wordssplit(/\s+/)
Collapse spaces/\s+/g → single space
Trim edges/^\s+|\s+$/g
Opposite\S

📋 \s vs space vs \S

Three related patterns for whitespace handling.

Whitespace
\s

All types

Literal
 

Space only

Non-space
\S

Inverse

Many gaps
\s+

Quantifier

Examples Gallery

Open DevTools Console (F12) or use Try-it links. Examples cover detection, splitting, normalization, trimming, and comparison with \S.

📚 Getting Started

Detect whether a string contains any whitespace character.

Example 1 — Test for Any Whitespace

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

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

How It Works

A single \s matches one whitespace character anywhere in the string. Compact strings with no separators never satisfy the pattern.

📈 Practical Patterns

Split, normalize, trim, and count with whitespace patterns.

Example 2 — Split Words on Any Whitespace

Break irregularly spaced text into an array of words.

JavaScript
const messy = "  one   two\tthree  ";

const words = messy.split(/\s+/);
console.log(words); // ["one", "two", "three"]

const multiline = "alpha\nbeta\tgamma";
console.log(multiline.split(/\s+/)); // ["alpha", "beta", "gamma"]
Try It Yourself

How It Works

split(/\s+/) treats one or more consecutive whitespace characters as a single delimiter. Leading and trailing gaps produce no empty entries.

Example 3 — Collapse Multiple Spaces to One

Normalize extra spacing in user-entered text.

JavaScript
const padded = "too    many     spaces";

const neat = padded.replace(/\s+/g, " ");
console.log(neat); // "too many spaces"

const tabs = "hello\t\tworld";
console.log(tabs.replace(/\s+/g, " ")); // "hello world"
Try It Yourself

How It Works

The global flag with /\s+/g replaces every whitespace run with a single space. Tabs and multiple spaces are handled uniformly.

Example 4 — Trim Leading and Trailing Whitespace

Remove whitespace from the start and end of a string with regex.

JavaScript
const raw = "   hello world   ";

const trimmed = raw.replace(/^\s+|\s+$/g, "");
console.log(trimmed); // "hello world"

// Built-in alternative:
console.log(raw.trim()); // "hello world"
Try It Yourself

How It Works

^\s+ removes leading whitespace; \s+$ removes trailing. For everyday trimming, String.trim() is simpler, but the regex shows how \s works with anchors.

Example 5 — Count Lines in a Text Block

Split on newline whitespace to count non-empty lines.

JavaScript
const log = "2026-01-01 OK\n2026-01-02 OK\n2026-01-03 FAIL";

const lines = log.split(/\n/);
console.log(lines.length); // 3

const words = log.split(/\s+/);
console.log(words); // ["2026-01-01", "OK", "2026-01-02", ...]
Try It Yourself

How It Works

Use \n for line-specific splits and \s+ for all-whitespace tokenization. See the \n tutorial for newline details.

🚀 Common Use Cases

  • Word splitting — tokenize input with split(/\s+/).
  • Space normalization — collapse double spaces in form data.
  • Blank detection — check for whitespace-only fields with /^\s*$/.
  • Log parsing — split lines and fields separated by tabs or spaces.
  • Input cleaning — trim and normalize before validation.
  • CSV-like data — split on \s+ when columns are space-delimited.

Important Considerations

  • Not just spaces\s includes tabs and newlines, unlike a literal space.
  • Prefer trim() — for simple edge trimming, String.trim() is clearer than regex.
  • Unicode spaces — default \s covers ASCII whitespace; exotic Unicode spaces may need the u flag.
  • Not null\0 (NUL) is not matched by \s.
  • Global flag — omitting g in replace() fixes only the first whitespace run.

🧠 How \s Matches Whitespace

1

Read character

The engine inspects the next character at the current position.

Scan
2

Check whitespace set

\s succeeds if the character is space, tab, newline, or related separator.

Match
3

Apply quantifier

With +, the engine greedily collects consecutive whitespace.

Extend
4

Continue pattern

Whitespace matched → advance. Visible char → fail or backtrack.

📝 Notes

  • \s matches space, tab, newline, carriage return, form feed, and vertical tab.
  • \S is the inverse (non-whitespace). See \S tutorial.
  • Individual tutorials: \n, \t (next page).
  • Next up: \t tab metacharacter specifically.
  • For most trimming, use trim(), trimStart(), and trimEnd().
  • Review \0 — null is not whitespace.

Browser & Runtime Support

The \s whitespace metacharacter is part of core JavaScript regular expression syntax.

Baseline · ES3+

RegExp \s

Supported in every browser and Node.js version. \s matches standard ASCII whitespace characters.

99% Universal syntax
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 everywhere. Use \s as the standard shorthand for matching whitespace.

Conclusion

The \s metacharacter is the fastest way to match whitespace in JavaScript regular expressions. It covers spaces, tabs, newlines, and related separators in one shorthand.

Use split(/\s+/) to tokenize words, replace(/\s+/g, " ") to normalize spacing, and remember the inverse \S for non-whitespace matching. Next, learn \t for tab characters specifically.

💡 Best Practices

✅ Do

  • Use split(/\s+/) for flexible word tokenization
  • Use /\s+/g to collapse irregular spacing
  • Know that \s includes tabs and newlines
  • Pair with \S when extracting visible tokens
  • Use trim() for simple edge cleanup

❌ Don’t

  • Assume \s matches only the space key
  • Forget the global flag when normalizing all gaps
  • Use regex trim when trim() is enough
  • Expect \s to match null bytes
  • Split on literal space when tabs or newlines are possible

Key Takeaways

Knowledge Unlocked

Five things to remember about RegExp \s

Match spaces, tabs, and line breaks with one shorthand.

5
Core concepts
📈 02

\s+

Runs.

Quantifier
🚫 03

split()

Words.

Parse
🔒 04

replace

Normalize.

Clean
🔢 05

\S

Inverse.

Pair

❓ Frequently Asked Questions

\s matches any single whitespace character: space, tab (\t), newline (\n), carriage return (\r), form feed (\f), and vertical tab (\v).
\s matches whitespace. \S is the uppercase 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+/). This handles multiple spaces, tabs, and newlines as delimiters.
No. The null character (\0, U+0000) is not included in the \s whitespace class in JavaScript.
The \s whitespace shorthand is core regex syntax since ES3. It works in every browser and Node.js version.
Did you know?

JavaScript’s \s and \S form an inverse pair, just like \d/\D and \w/\W. Lowercase matches a set; uppercase matches everything except that set.

Continue to \t tab metacharacter

Learn how to match 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