大网数据广告活动
Web 标准与前端开发

Character class escape: \\d, \\D, \\w, \\W, \\s, \\S

· 52CE 我爱测

A **character class escape** is an escape sequence that represents a set of characters.

A character class escape is an escape sequence that represents a set of characters.

Syntax

\d, \D
\s, \S
\w, \W

[!NOTE] , is not part of the syntax.

Description

Unlike character escapes, character class escapes represent a predefined set of characters, much like a character class. The following character classes are supported:

  • \d
    • : Matches any digit character. Equivalent to [0-9].
  • \w
    • : Matches any word character, where a word character includes letters (A–Z, a–z), numbers (0–9), and underscore (_). If the regex is Unicode-aware and the i flag is set, it also matches other Unicode characters that get canonicalized to one of the characters above through case folding.
  • \s

The uppercase forms \D, \W, and \S create complement character classes for \d, \w, and \s, respectively. They match any character that is not in the set of characters matched by the lowercase form.

Unicode character class escapes start with \p and \P, but they are only supported in Unicode-aware mode. In Unicode-unaware mode, they are identity escapes for the p or P character.

Character class escapes can be used in character classes. However, they cannot be used as boundaries of character ranges, which is only allowed as a deprecated syntax for web compatibility, and you should not rely on it.

Examples

Splitting by whitespace

The following example splits a string into an array of words, supporting all kinds of whitespace separators:

function splitWords(str) {
  return str.split(/\s+/);
}

splitWords(`Look at the stars
Look  how they\tshine for you`);
// ['Look', 'at', 'the', 'stars', 'Look', 'how', 'they', 'shine', 'for', 'you']

Specifications

Browser compatibility

See also

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。