JavaScript RegExp \S Metacharacter

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

What You’ll Learn

The \S metacharacter matches any single character that is not whitespace. It is the inverse of \s, equivalent to [^\s], and essential when you need to tokenize words, detect visible content, or validate input with no spaces.

01

Non-space

\S

02

Shorthand

[^\s]

03

Inverse

Opposite of \s

04

Quantifiers

\S+

05

Tokenize

match(/\S+/g)

06

Validate

/^\S+$/

Introduction

Whitespace—spaces, tabs, and line breaks—separates words in most text. The \S metacharacter matches everything except those invisible separators, making it perfect for finding visible content.

One \S matches exactly one non-whitespace character. To capture full words or tokens, combine \S with + to match one or more consecutive non-whitespace characters.

Understanding the \S Metacharacter

\S is a negated predefined character class escape. In JavaScript it matches any character except whitespace: space, tab (\t), newline (\n), carriage return (\r), and form feed (\f).

JavaScript
/\S/.test("   ");        // false (spaces only)
/\S/.test("hello");      // true  (letters)
/\S/.test("  hi  ");     // true  ("h" matches)

"hello   world".match(/\S+/g);  // ["hello", "world"]
"   ".replace(/\S/g, "x");       // "   " (no change)

The lowercase form \s matches whitespace only. Think of \S as “not space”—letters, digits, and punctuation all qualify.

💡
Beginner Tip

To split messy text into words without worrying about multiple spaces, write text.match(/\S+/g). Each match is a contiguous run of visible characters.

How to Use \S in JavaScript

Use \S in detection, tokenization, validation, and parsing workflows:

JavaScript
/\S/.test("   ");                    // false (blank)
"  one  two  three  ".match(/\S+/g); // ["one", "two", "three"]
/^\S+$/.test("username");            // true (no spaces)
"    start".search(/\S/);            // 4 (first visible char)

Pair \S with anchors (^, $), quantifiers (+, *), and methods like match(), search(), and test().

📝 Syntax

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

Common patterns

  • /\S+/g — extract all word-like tokens from text.
  • /^\S+$/ — validate input contains no whitespace.
  • /\S/ — check whether a string has any visible content.
  • /^\s*\S/ — detect leading whitespace before content.

⚡ Quick Reference

GoalPattern
One non-whitespace\S
Word token\S+
All tokens in text/\S+/g
No spaces allowed/^\S+$/
Same as \S[^\s]
Opposite\s

📋 \S vs [^\s] vs \s

Three related patterns for non-whitespace and whitespace.

Non-space
\S

Shorthand

Class
[^\s]

Equivalent

Whitespace
\s

Inverse

Many tokens
\S+

Quantifier

Examples Gallery

Open DevTools Console (F12) or use Try-it links. Examples cover detection, tokenization, validation, index lookup, and parsing tagged text.

📚 Getting Started

Detect whether a string contains any visible (non-whitespace) character.

Example 1 — Test for Any Non-Whitespace

Return true when the string is not blank or whitespace-only.

JavaScript
console.log(/\S/.test("   "));       // false
console.log(/\S/.test("hello"));     // true
console.log(/\S/.test("  hi  "));    // true
Try It Yourself

How It Works

A single \S matches one non-whitespace anywhere in the string. Pure whitespace strings like " " never satisfy the pattern.

📈 Practical Patterns

Tokenize, validate, locate, and parse with non-whitespace patterns.

Example 2 — Tokenize Words With \S+

Extract word-like tokens from text with irregular spacing.

JavaScript
const messy = "  hello   world\tfoo  ";

const words = messy.match(/\S+/g);
console.log(words); // ["hello", "world", "foo"]

const line = "Price: $19  today";
const tokens = line.match(/\S+/g);
console.log(tokens); // ["Price:", "$19", "today"]
Try It Yourself

How It Works

\S+ greedily collects consecutive non-whitespace characters. Whitespace acts as a boundary, splitting the string into separate tokens.

Example 3 — Validate Input With No Spaces

Ensure a username or slug contains no whitespace characters.

JavaScript
const noSpaces = /^\S+$/;

console.log(noSpaces.test("username"));    // true
console.log(noSpaces.test("user_name"));   // true
console.log(noSpaces.test("user name"));   // false
console.log(noSpaces.test("   "));         // false
Try It Yourself

How It Works

^ and $ anchor the match to the full string. \S+ requires one or more non-whitespace characters with no spaces, tabs, or newlines allowed.

Example 5 — Parse Hashtags From a Sentence

Extract #tag tokens from social-style text using non-whitespace runs.

JavaScript
const post = "Learning #JavaScript and #RegExp today!";

const tokens = post.match(/\S+/g);
const tags = tokens.filter(function (t) { return t.startsWith("#"); });

console.log(tags); // ["#JavaScript", "#RegExp"]
Try It Yourself

How It Works

\S+/g splits the post into tokens first. Filtering by prefix then isolates hashtags—a practical two-step pattern for parsing user-generated text.

🚀 Common Use Cases

  • Blank check — reject whitespace-only form fields with /\S/.test(value).
  • Word tokenization — split irregular text into tokens using \S+.
  • Username validation — enforce no spaces with /^\S+$/.
  • Indent detection — find the first visible column with search(/\S/).
  • Log parsing — extract non-whitespace fields from space-delimited records.
  • Content filtering — distinguish empty strings from strings with visible characters.

Important Considerations

  • One vs many — lone \S matches one character; use + for full tokens.
  • Not the same as letters\S includes digits and punctuation, not just A–Z.
  • Unicode spaces — default \s and \S cover common ASCII whitespace; exotic Unicode spaces may need the u flag.
  • Trim alternative — for simple trimming, String.trim() is often clearer than regex.
  • Same as [^\s] — pick one style and stay consistent within a codebase.

🧠 How \S Matches Non-Whitespace

1

Read character

The engine inspects the next character at the current position.

Scan
2

Check not whitespace

\S succeeds only if the character is NOT space, tab, or line break.

Match
3

Apply quantifier

With +, the engine repeats until whitespace or end of string.

Extend
4

Continue pattern

Non-whitespace matched → advance. Whitespace found → fail or backtrack.

📝 Notes

  • \S equals [^\s] in standard JavaScript regex.
  • \s matches space, tab, newline, carriage return, and form feed.
  • Review \D non-digit and \n newline metacharacters.
  • Next up: \W metacharacter for non-word characters.
  • For letters only, use /^[a-zA-Z]+$/ instead of /^\S+$/.
  • Combine with \b for word boundaries: \b\S+\b approximates whole tokens.

Browser & Runtime Support

The \S non-whitespace metacharacter is part of core JavaScript regular expression syntax.

Baseline · ES3+

RegExp \S

Supported in every browser and Node.js version. \S and [^\s] behave identically for standard whitespace.

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 non-whitespace.

Conclusion

The \S metacharacter is the fastest way to match non-whitespace in JavaScript regular expressions. It covers letters, digits, punctuation, and symbols—everything except spaces, tabs, and line breaks.

Use \S+ to tokenize words, /\S/.test() to reject blank input, and remember that it is the uppercase inverse of \s. Next, learn \W for non-word character matching.

💡 Best Practices

✅ Do

  • Use /\S+/g to tokenize irregularly spaced text
  • Use /\S/.test() to check for non-blank input
  • Anchor with ^ and $ for no-space validation
  • Know that \S and [^\s] are equivalent
  • Pair with \s when parsing space-delimited data

❌ Don’t

  • Expect \S alone to match full words
  • Assume /^\S+$/ means “letters only”
  • Use regex for trimming when trim() is simpler
  • Forget that punctuation counts as non-whitespace
  • Mix \S and manual [^\s] randomly in one project

Key Takeaways

Knowledge Unlocked

Five things to remember about RegExp \S

Match anything except whitespace.

5
Core concepts
🚫 02

= [^\s]

Same set.

Compare
📈 03

\S+

Tokens.

Quantifier
🔒 04

/^\S+$/

No spaces.

Validate
🔢 05

\s

Inverse.

Pair

❓ Frequently Asked Questions

\S matches any single character that is NOT whitespace. Letters, digits, punctuation, and symbols all satisfy \S. Spaces, tabs, and newlines do not.
\s matches whitespace (space, tab, newline, form feed, carriage return). \S is the uppercase inverse and matches everything except those characters.
Yes. In standard JavaScript regex, \S and [^\s] are equivalent—they both match one non-whitespace character.
Use match with a quantifier: str.match(/\S+/g). Each \S+ run is a contiguous non-whitespace token—ideal for splitting messy text into words.
By itself, \S matches exactly one non-whitespace character. Add + for one or more (\S+) or * for zero or more (\S*) to match longer tokens.
The \S non-whitespace shorthand is core regex syntax since ES3. It works in every browser and Node.js version.
Did you know?

String.split(/\s+/) splits on whitespace, while match(/\S+/g) extracts non-whitespace tokens. They are complementary approaches—split removes separators, match keeps the visible parts.

Continue to \W non-word metacharacter

Learn how uppercase W matches any character that is not a word character.

\W 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