JavaScript RegExp \W Metacharacter

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

What You’ll Learn

The \W metacharacter matches any single character that is not a word character. Word characters are letters, digits, and underscore (_). Everything else—spaces, hyphens, punctuation, and symbols—matches \W.

01

Non-word

\W

02

Shorthand

[^\w]

03

Inverse

Opposite of \w

04

Quantifiers

\W+

05

Strip

replace(/\W/g, "")

06

Split

split(/\W+/)

Introduction

When parsing user input, cleaning data, or splitting sentences, you often need to target punctuation and separators rather than letters and numbers. The \W metacharacter matches any character that is not part of the word-character set.

One \W matches exactly one non-word character. To match a run of punctuation or whitespace separators, combine \W with + or use the global flag with replace().

Understanding the \W Metacharacter

\W is a negated predefined character class escape. In JavaScript a word character (\w) is equivalent to [A-Za-z0-9_]. Therefore \W matches everything except letters, digits, and underscore.

JavaScript
/\W/.test("hello");       // false (all word chars)
/\W/.test("hello!");      // true  ("!" matches)
/\W/.test("user_name");   // false (_ is a word char)
/\W/.test("user-name");   // true  ("-" matches)

"hello, world!".match(/\W+/g);  // [", ", "!"]

The lowercase form \w matches word characters only. Remember: underscore counts as a word character, but hyphen does not.

💡
Beginner Tip

To create a simple slug from a title, write title.replace(/\W+/g, "-"). Non-word runs become hyphens, though you may still want to trim and lowercase separately.

How to Use \W in JavaScript

Use \W in detection, extraction, cleaning, splitting, and validation workflows:

JavaScript
/\W/.test("abc123");                 // false
"hello, world!".match(/\W+/g);       // [", ", "!"]
"Hello, World!".replace(/\W/g, ""); // "HelloWorld"
"one,two;three".split(/\W+/);        // ["one", "two", "three"]

Pair \W with anchors, quantifiers, and methods like test(), match(), replace(), and split().

📝 Syntax

JavaScript
\W              // one non-word character
\W+             // one or more non-word chars
\W*             // zero or more non-word chars
/\W/g           // global: every non-word char
\w              // one word char (inverse of \W)

Common patterns

  • /\W+/g — match runs of punctuation or separators.
  • /\W/g + replace("", ...) — remove all non-word characters.
  • split(/\W+/) — break text on non-word boundaries.
  • /^\w+$/ — validate word characters only (no \W allowed).

⚡ Quick Reference

GoalPattern
One non-word char\W
Punctuation run\W+
Remove symbols/\W/g + replace("", ...)
Split on separatorssplit(/\W+/)
Same as \W[^\w]
Opposite\w

📋 \W vs [^\w] vs \w

Three related patterns for non-word and word characters.

Non-word
\W

Shorthand

Class
[^\w]

Equivalent

Word char
\w

Inverse

Word set
[A-Za-z0-9_]

Same as \w

Examples Gallery

Open DevTools Console (F12) or use Try-it links. Examples cover detection, extraction, symbol removal, splitting, and alphanumeric validation.

📚 Getting Started

Detect whether a string contains any non-word character.

Example 1 — Test for Any Non-Word Character

Return true when punctuation, spaces, or symbols appear in the text.

JavaScript
console.log(/\W/.test("hello"));       // false
console.log(/\W/.test("hello!"));      // true
console.log(/\W/.test("user_name"));   // false (_ is word char)
console.log(/\W/.test("user-name"));   // true
Try It Yourself

How It Works

A single \W matches one non-word character anywhere in the string. Pure word-character strings like "hello" or "user_name" never satisfy the pattern.

📈 Practical Patterns

Extract, clean, split, and validate with non-word patterns.

Example 2 — Extract Punctuation and Separators

Find every run of non-word characters in a sentence.

JavaScript
const sentence = "Hello, world! How are you?";

const separators = sentence.match(/\W+/g);
console.log(separators);
// [", ", "! ", " ", " ", "?"]

const mixed = "price=$19.99";
console.log(mixed.match(/\W+/g)); // ["=", "."]
Try It Yourself

How It Works

\W+ greedily collects consecutive non-word characters. Word characters act as boundaries between matches.

Example 3 — Strip All Non-Word Characters

Remove punctuation and symbols, keeping letters, digits, and underscores.

JavaScript
const title = "Hello, World!";

const cleaned = title.replace(/\W/g, "");
console.log(cleaned); // "HelloWorld"

const email = "user@email.com";
console.log(email.replace(/\W/g, "")); // "useremailcom"
Try It Yourself

How It Works

The global flag with /\W/g replaces every non-word character with an empty string. Underscores survive because they are word characters.

Example 4 — Split Text on Non-Word Boundaries

Break a comma- or semicolon-separated list into individual tokens.

JavaScript
const csv = "one,two;three four";

const parts = csv.split(/\W+/);
console.log(parts); // ["one", "two", "three", "four"]

const tags = "js,regex,pattern";
console.log(tags.split(/\W+/)); // ["js", "regex", "pattern"]
Try It Yourself

How It Works

split(/\W+/) divides the string wherever one or more non-word characters appear. Commas, semicolons, and spaces all act as delimiters.

Example 5 — Validate Alphanumeric Input

Ensure a field contains only word characters (letters, digits, underscore).

JavaScript
const wordOnly = /^\w+$/;

console.log(wordOnly.test("abc123"));    // true
console.log(wordOnly.test("user_name")); // true
console.log(wordOnly.test("user-name")); // false (hyphen)
console.log(wordOnly.test("hello!"));    // false (punctuation)

// Equivalent check using \W:
console.log(!/\W/.test("abc123"));       // true
Try It Yourself

How It Works

/^\w+$/ allows only word characters. Alternatively, !/\W/.test(str) returns true when no non-word character exists anywhere in the string.

🚀 Common Use Cases

  • Punctuation detection — flag strings that contain symbols with /\W/.test().
  • Data cleaning — remove non-alphanumeric characters from imported text.
  • Token splitting — break CSV or tag lists with split(/\W+/).
  • Username rules — reject hyphens and dots using /^\w+$/.
  • Slug generation — replace \W+ runs with hyphens for URL-friendly strings.
  • Password hints — require at least one symbol by testing for \W.

Important Considerations

  • Underscore is a word char_ matches \w, not \W.
  • One vs many — lone \W matches one character; use + for separator runs.
  • Global flag — omitting g in replace() removes only the first non-word character.
  • Not the same as \S\W excludes word chars; \S excludes whitespace only.
  • ASCII word set — default \w is [A-Za-z0-9_]; Unicode letters need the u flag.

🧠 How \W Matches Non-Word Characters

1

Read character

The engine inspects the next character at the current position.

Scan
2

Check not word char

\W succeeds only if the character is NOT A–Z, 0–9, or underscore.

Match
3

Apply quantifier

With + or global replace, the engine repeats the check.

Extend
4

Continue pattern

Non-word matched → advance. Word char found → fail or backtrack.

📝 Notes

  • \W equals [^\w] in standard JavaScript regex.
  • \w equals [A-Za-z0-9_] (letters, digits, underscore).
  • Review \S non-whitespace and \b word boundary.
  • Next up: \B non-word-boundary metacharacter.
  • For letters only (no digits or underscore), use /^[a-zA-Z]+$/ instead of /^\w+$/.
  • Combine with \b for whole-word matching: \b\w+\b.

Browser & Runtime Support

The \W non-word metacharacter is part of core JavaScript regular expression syntax.

Baseline · ES3+

RegExp \W

Supported in every browser and Node.js version. \W and [^\w] behave identically for standard word 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
\W Excellent

Bottom line: Safe everywhere. Use \W as the standard shorthand for matching non-word characters.

Conclusion

The \W metacharacter is the fastest way to match non-word characters in JavaScript regular expressions. It targets spaces, punctuation, hyphens, and symbols—everything except letters, digits, and underscore.

Use \W+ to find separator runs, /\W/g with replace() to strip symbols, and remember that underscore is a word character. Next, learn \B for non-word-boundary matching.

💡 Best Practices

✅ Do

  • Use /\W/g to strip punctuation from imported data
  • Use split(/\W+/) for flexible delimiter parsing
  • Remember underscore is a word character
  • Know that \W and [^\w] are equivalent
  • Pair with \w when building slug or ID patterns

❌ Don’t

  • Expect hyphens to match \w (they match \W)
  • Forget the global flag when removing all symbols
  • Confuse \W with \S (different sets)
  • Assume /^\w+$/ means “letters only”
  • Mix \W and manual [^\w] randomly in one project

Key Takeaways

Knowledge Unlocked

Five things to remember about RegExp \W

Match anything except word characters.

5
Core concepts
📝 02

= [^\w]

Same set.

Compare
📈 03

\W+

Separators.

Quantifier
🔒 04

/\W/g

Strip symbols.

Replace
🔢 05

\w

Inverse.

Pair

❓ Frequently Asked Questions

\W matches any single character that is NOT a word character. Word characters are letters A–Z, digits 0–9, and underscore (_). Spaces, hyphens, and punctuation all satisfy \W.
\w matches word characters (letters, digits, underscore). \W is the uppercase inverse and matches everything except those characters—spaces, symbols, and punctuation.
Yes. In standard JavaScript regex, \W and [^\w] are equivalent—they both match one non-word character.
No. Underscore (_) is a word character and matches \w, not \W. Hyphens, spaces, and @ symbols do match \W.
Use replace with the global flag: str.replace(/\W/g, ""). Every non-word character is removed, leaving letters, digits, and underscores.
The \W non-word shorthand is core regex syntax since ES3. It works in every browser and Node.js version.
Did you know?

JavaScript’s three uppercase inverse shorthands—\D, \S, and \W—complete the lowercase trio \d, \s, and \w. Uppercase always means “everything except” the lowercase form.

Continue to \B non-word-boundary metacharacter

Learn how uppercase B matches positions that are not word boundaries.

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