Shorthand Classes
Some character classes are needed so often that they have short names. Each one is a backslash plus a letter, and the uppercase version is the opposite of the lowercase one.
| Shorthand | Means (JavaScript) | Equivalent class |
|---|---|---|
\d |
digit | [0-9] |
\D |
non-digit | [^0-9] |
\w |
"word" character | [A-Za-z0-9_] |
\W |
non-word character | [^A-Za-z0-9_] |
\s |
whitespace (space, tab, newline, and Unicode spaces) | — |
\S |
non-whitespace | — |
\d — digits
/\d\d:\d\d/g
Doors open 18:30, show starts 19:00 (not 7:5).2 matches
#1 "18:30" at index 11
#2 "19:00" at index 30
\w — word characters
\w matches letters, digits and the underscore. It is handy for identifiers and usernames:
/@\w+/g
Thanks @linh_dev and @Quan99 — cc @-nobody2 matches
#1 "@linh_dev" at index 7
#2 "@Quan99" at index 21
Note: In JavaScript
\wis ASCII-only, even with theuflag. Inngọc,\w+stops atọ. Python 3's\wis Unicode-aware by default and matches it. When you need letters from any language in JavaScript, use\p{L}(Unicode lesson).
/\w+/g
ngọc anh3 matches
#1 "ng" at index 0
#2 "c" at index 3
#3 "anh" at index 5
\s — whitespace
\s matches spaces, tabs, newlines, carriage returns, form feeds and Unicode spaces such as the non-breaking space. \s+ is the classic way to match "a gap of any size":
/\S+/g
one two three
four4 matches
#1 "one" at index 0
#2 "two" at index 6
#3 "three" at index 10
#4 "four" at index 16
\S+ ("one or more non-whitespace characters") splits the text into tokens no matter how they are separated — multiple spaces, a tab, or a line break.
Combining shorthands in a class
Shorthands can go inside square brackets together with other characters. [\w.-] means "a word character, a dot or a hyphen":
/[\w.-]+@[\w-]+\.\w+/g
Write to mai.tran@mail-box.vn or b@x.io2 matches
#1 "mai.tran@mail-box.vn" at index 9
#2 "b@x.io" at index 33
The opposite trick: match anything
[\s\S] means "whitespace or non-whitespace" — in other words, any character including a newline. You will see it in older code as a way to cross line breaks (the modern alternative is the s flag, covered in the next lesson).
/<b>[\s\S]*<\/b>/
<b>bold
text</b>1 match
#1 "<b>bold\ntext</b>" at index 0
In code
const raw = " Price:\t 1 200 000 VND ";
console.log(raw.replace(/\s+/g, " ").trim());
console.log(raw.replace(/\D/g, ""));
console.log(raw.split(/\s+/).filter(Boolean));Price: 1 200 000 VND
1200000
[ 'Price:', '1', '200', '000', 'VND' ]
Test yourself
Which characters does \w match in JavaScript?
- Letters only
- Letters, digits and underscore (ASCII)
- Any non-space character
- Letters from any language
What is \D equivalent to?
[0-9][^0-9]\d+[a-z]
What does "a b".split(/\s+/) produce?
['a', '', 'b']['a', 'b']['a b']['a', ' ', 'b']