Literal characters
Most characters match themselves: /cat/ matches the text cat.
Special characters (metacharacters)
Some characters have a special meaning. To match them literally, put a backslash in front: ., *, +, ?, ^, $, (, ), [, ], {, }, |, \.
console.log(/3.5/.test("3x5")); // → true (. matches any character)
console.log(/3\.5/.test("3x5")); // → false (\. matches only a real dot)
console.log(/3\.5/.test("3.5")); // → true
Shorthand character classes
| Pattern | Matches |
|---|---|
\d | a digit (0–9) |
\w | a “word” character: letter, digit or _ |
\s | whitespace (space, tab, line break) |
. | any character except a line break |
\D, \W, \S | the opposites |
console.log("Room 42".match(/\d/)[0]); // → 4
console.log(/\s/.test("two words")); // → true
console.log(/^\w+$/.test("hello_1")); // → true
console.log(/^\w+$/.test("hello 1")); // → false
Your own sets with [ ]
Square brackets match one character from a set.
console.log(/[aeiou]/.test("sky")); // → false
console.log(/[aeiou]/.test("sea")); // → true
console.log(/^[A-Z]/.test("Hello")); // → true (range)
console.log(/[^0-9]/.test("123")); // → false (^ inside brackets means NOT)
Ranges: [a-z], [A-Z], [0-9], and combinations: [a-zA-Z0-9_].
Anchors: start and end
^ matches the start of the text and $ the end. Without them, a pattern can match anywhere.
console.log(/cat/.test("concatenate")); // → true (found somewhere inside)
console.log(/^cat$/.test("concatenate")); // → false (the whole text must be "cat")
console.log(/^cat$/.test("cat")); // → true
For validation you almost always want ^ and $, so the whole input must match.
Word boundary
\b matches the edge of a word.
console.log(/\bcat\b/.test("a cat sat")); // → true
console.log(/\bcat\b/.test("concatenate")); // → false
Alternatives
| means “or”.
console.log(/^(red|green|blue)$/.test("green")); // → true
console.log(/^(red|green|blue)$/.test("pink")); // → false