Course contentsShow
← JavaScript
Lesson 1738 of 2,72336. Regular ExpressionsFree lesson

Unicode and Character Classes

\w, \d, and \s only match ASCII by default; use the u flag for proper Unicode support.

Unicode and Character Classes

You'll learn why basic character classes fail with non-ASCII characters and how to fix it with the u flag.

The ASCII Limitation

By default, JavaScript's shorthand character classes—\w (word characters), \d (digits), and \s (whitespace)—only match ASCII characters. This means \w matches [A-Za-z0-9_], \d matches [0-9], and \s matches common ASCII whitespace.

This creates problems with international text. For example, \w won't match accented letters like é, ñ, or ü, and \d won't match digits from other scripts like Arabic numerals ٠١٢ or Devanagari digits ०१२.

The Unicode Flag (u)

The u flag tells JavaScript to interpret your regex with full Unicode awareness:

// Without 'u' - fails with non-ASCII
/^\w+$/.test('café');    // false - 'é' not matched
/^\d+$/.test('٣٤٥');     // false - Arabic digits not matched

// With 'u' - proper Unicode support
/^\w+$/u.test('café');   // true - 'é' is a word character
/^\d+$/u.test('٣٤٥');    // true - recognizes Arabic digits

The u flag also handles multi-byte Unicode characters correctly (like emojis) and enables Unicode property escapes for more specific matching.

Key Takeaway: Always use the u flag when working with international text or non-ASCII characters; without it, \w, \d, and \s are limited to basic ASCII matching, causing unexpected failures with real-world multilingual content.