Matching characters
Literals, the dot and escaping
Goal: Write patterns from literal characters and use . and \ correctly · 8 min
A regular expression (regex) is a compact description of a set of strings. A search engine for text: instead of looking for one word, you describe the shape of what you want.
In JavaScript a regex sits between slashes: /cat/. The simplest pattern is made of literals: every ordinary character matches itself. /cat/ matches the three letters "cat" in a row, anywhere in the text, so it finds "cat" inside "concatenate".
Matching is case-sensitive by default: /cat/ does not match "Cat".
Some characters have a special meaning and are called metacharacters: . ^ $ * + ? ( ) [ ] { } | \
- The dot
.matches any single character except a line break:/c.t/matches "cat", "cut", "c7t" and "c t". - To match a metacharacter itself, put a backslash before it:
/3\.5/matches "3.5" only, while/3.5/also matches "385".
Rule of thumb: if a pattern should contain a dot, a plus or a bracket as plain text, escape it.
Worked example: Finding a price
- Goal: match the text "9.99" exactly.
/9.99/would also match "9a99" because the dot is a wildcard.- Escape the dot:
/9\.99/matches only "9.99".
console.log(/9\.99/.test("9.99"), /9\.99/.test("9a99"), /9.99/.test("9a99"));Output:
true false true