UNB/ CS/ David Bremner/ teaching/ cs2613/ books/ mdn/ Reference/ Regular expressions/ ""Character

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:

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