Quiz
Warm-up from lesson 8-2: `"" ?? "default"` evaluates to what?
A pattern language for strings
A regular expression (regex) describes a text pattern. In JavaScript you write one between slashes, and the simplest use is pattern.test(string), which returns true or false.
Regex exists because "find text of this shape" written with plain string methods turns into unreadable loops of indexOf and slice. It is the engine behind input validation, log searching, editor find-and-replace, and URL routing — a few characters of pattern replacing dozens of lines of code.
The core vocabulary:
| piece | matches |
|---|---|
cat | the literal letters c a t |
\d | one digit (\w word char, \s whitespace) |
. | any single character |
x+ | one or more x (x* zero or more, x? optional) |
x{5} | exactly five x (x{2,4} two to four) |
[abc] | one character from the set ([^abc] NOT in the set) |
^ and $ | start and end of the string |
Without anchors a regex matches anywhere inside the string, which is the number one source of validation bugs.
Code exercise · javascript
Run it. The anchored zip pattern demands the WHOLE string be five digits. The unanchored version happily matches five digits hiding inside a longer string.
Quiz
You validate usernames with `/\w+/` and someone submits `"!!!bob!!!"`. Does test() accept it?
Alternation and escaping
Two more pieces complete the starter kit:
a|bis alternation: match either side. Wrap it in parentheses to limit its reach —/\.(png|jpe?g|gif)$/means a literal dot, then one of three extensions, then end of string.- Characters the pattern language reserves (
. + ? ( ) [ ] { } $ ^ | \) must be escaped with a backslash to be matched literally. An unescaped.matches ANY character, so/one.png$/happily accepts"onexpng"— a real bug class in file-type checks.
Code exercise · javascript
Run it. The escaped `\.` demands a real dot, so `trickypng` fails, while the alternation accepts all three extensions (`jpe?g` covers jpg and jpeg).
Code exercise · javascript
Your turn. Build `time24`, a regex for 24-hour times like `09:45`: exactly two digits, a colon, two digits, anchored at both ends. (Do not worry about rejecting 99:99.)