liveBook · Manning

Character class

As explained in Secrets of the JavaScript Ninja, Second Edition

A regular expression construct in square brackets that matches one character from a specified set or range, optionally negated.

Need one character from several possibilities? Put them in square brackets. `[abc]` matches `a`, `b`, or `c`—one character, not the three-character string `abc`. section 10.2.2

Three useful forms:

  • `[abc]` selects one listed character. section 10.2.2
  • `[^abc]` selects one character other than `a`, `b`, or `c`. The caret negates the set when it follows the opening bracket; outside brackets, `^` anchors a pattern to the start of a string. section 10.2.2 section 10.7
  • `[a-m]` selects one character in the inclusive range from `a` through `m`. section 10.2.2

Matching across a newline

The dot in `/.*/` stops before the newline in `"<b>Hello</b>\n<i>world!</i>"`. The class `[\S\s]` accepts either a non-whitespace or a whitespace character, so `/[\S\s]*/` matches the whole string. Here, `*` repeats the one-character choice. section 10.6.1

Listing 10.11. Matching all characters, including newlines
 const html = "<b>Hello</b>\n<i>world!</i>";                     #A
 assert(/.*/.exec(html)[0] === "<b>Hello</b>",                   #B
         "A normal capture doesn't handle endlines.");
 assert(/[\S\s]*/.exec(html)[0] ===                              #C
         "<b>Hello</b>\n<i>world!</i>",                          #C
         "Matching everything with a character set.");           #C
 assert(/(?:.|\s)*/.exec(html)[0] ===                            #D
         "<b>Hello</b>\n<i>world!</i>",                          #D
         "Using a non-capturing group to match everything.");    #D

Compare the assertions: the dot stops at the newline, while the character class and a non-capturing alternation reach the end. section 10.6.1

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Defines explicit, negated, and ranged classes, then works through a newline-matching idiom without an exhaustive regex treatment.
Examples
Uses `[abc]`, `[^abc]`, `[a-m]`, and assertions comparing `/.*/` with `/[\S\s]*/` on a string containing a newline.
What it assumes
Assumes familiarity with JavaScript strings and regex notation while defining character classes from their basic bracket form.
What you can do after
Apply it via JavaScript regular expressions to choose characters from sets and match across newlines.
How it connects
Links character classes to quantifiers, predefined character terms, alternation, and the dot operator.

Also explained in

Compare how 9 books explain character class →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.