Literal Characters
The simplest regex is just ordinary text. Letters, digits, spaces and most punctuation are literal characters: each one matches exactly itself. The pattern blue means "the character b, followed by l, followed by u, followed by e".
/blue/g
Blue skies, a blue car and bluebells.2 matches
#1 "blue" at index 14
#2 "blue" at index 27
Two things to notice:
- Matching is case-sensitive.
Blueat the start was skipped, becauseBandbare different characters. - Matches can sit inside longer words.
bluebellscontainsblue, so it matched.
Case-insensitive matching
Add the i flag to treat upper and lower case as equal:
/blue/gi
Blue skies, a blue car and BLUEBELLS.3 matches
#1 "Blue" at index 0
#2 "blue" at index 14
#3 "BLUE" at index 27
The tester shows the text as it appears in the input, so you can see which spelling was found.
Spaces and punctuation are literal too
A space in the pattern matches one space in the text — no more, no less. That makes "red car" different from "red car" (two spaces):
/red car/g
red car, red car, redcar, red car2 matches
#1 "red car" at index 0
#2 "red car" at index 27
Most punctuation such as , - : ; ! @ # % = and " is literal as well:
/user@site/g
Contact: user@site or admin@site, not user-site.1 match
#1 "user@site" at index 9
How the engine scans
The engine tries the pattern at index 0, then index 1, then 2, and so on. At each position it compares the pattern character by character. As soon as one character fails it moves on to the next starting position. When a match is found with the g flag, it continues searching after the end of that match — matches never overlap.
/aa/g
aaaaa2 matches
#1 "aa" at index 0
#2 "aa" at index 2
Five as contain four overlapping aa pairs, but only two non-overlapping matches are reported; the final a is left over.
Which characters are not literal?
These twelve-or-so characters have special meanings and are called metacharacters:
| Character(s) | Special meaning (lessons ahead) |
|---|---|
. |
any character |
* + ? { } |
quantifiers (repetition) |
^ $ |
anchors (start / end) |
[ ] |
character classes |
( ) |
groups |
| |
alternation ("or") |
\ |
escape |
/ |
ends a JavaScript regex literal |
To match one of them literally you escape it with a backslash — that is the topic of the next lesson.
Literal matching in code
When all you need is a fixed string, plain string methods are often simpler than a regex. They give the same answer here:
const s = "Blue skies, a blue car and bluebells.";
console.log(s.indexOf("blue"));
console.log(s.search(/blue/));
console.log(s.toLowerCase().split("blue").length - 1);14
14
3
Reach for a regex when the text you want varies — that is where the following lessons come in.
Test yourself
Which strings does /cat/ (no flags) match in Cat catalog?
Catonlycatinsidecatalogonly- Both
- Neither
How many matches does /oo/g find in oooo?
- 1
- 2
- 3
- 4