The Dot
The dot . is the most general metacharacter: it matches any single character except a line break. h.t matches hat, hit, hot, h t and even h#t.
/h.t/g
hat hit h t h#t ht heat4 matches
#1 "hat" at index 0
#2 "hit" at index 4
#3 "h t" at index 8
#4 "h#t" at index 12
ht has no character between h and t, and heat has two — the dot always stands for exactly one character.
What counts as a line break?
In JavaScript the dot refuses to match these line terminators:
| Character | Escape | Name |
|---|---|---|
| U+000A | \n |
line feed (Unix newline) |
| U+000D | \r |
carriage return (part of Windows \r\n) |
| U+2028 |
| line separator |
| U+2029 |
| paragraph separator |
So .+ stops at the end of each line:
/.+/g
first line
second line2 matches
#1 "first line" at index 0
#2 "second line" at index 11
The s (dotAll) flag
With the s flag the dot matches line breaks too. Compare the same pattern with and without it:
/start.*end/
start of the story
...and the endNo match
/start.*end/s
start of the story
...and the end1 match
#1 "start of the story\n...and the end" at index 0
Note: Python calls this flag
re.DOTALL(orre.S); in Java it isPattern.DOTALL; inline you can often write(?s)at the start of the pattern — but JavaScript does not support inline(?s).
The dot is usually too generous
Because the dot matches almost anything, patterns built on it tend to match more than you planned. A naive time pattern accepts garbage:
/\d\d.\d\d/g
12:30 12.30 12x30 12345674 matches
#1 "12:30" at index 0
#2 "12.30" at index 7
#3 "12x30" at index 14
#4 "12345" at index 21
Replace the dot with what you actually allow — here a class of separators:
/\d\d[:.]\d\d/g
12:30 12.30 12x30 12345672 matches
#1 "12:30" at index 0
#2 "12.30" at index 7
Tip: Treat
.as a last resort. When you know the set of allowed characters, a class like[^,]or[\w-]is safer and often faster.
A dot is not a literal dot
Remember: to match a real full stop you write \. — or put it in a class, [.], where the dot is always literal.
const files = ["report.pdf", "reportXpdf", "notes.txt"];
for (const f of files) {
console.log(f, /^\w+\.pdf$/.test(f), /^\w+.pdf$/.test(f));
}report.pdf true true
reportXpdf false true
notes.txt false false
Test yourself
Without flags, which character does . NOT match in JavaScript?
- A space
- A tab
- A newline
\n - A digit
How many characters does a.c match between a and c?
- Zero or one
- Exactly one
- One or more
- Any number
Which pattern matches a literal dot?
.[.].?(.)