Course contentsShow
← JavaScript
Lesson 1736 of 2,72336. Regular ExpressionsFree lesson

Dot Doesn't Match Newlines

The . metacharacter excludes \n by default; use the s flag or [\s\S] for multiline.

Dot Doesn't Match Newlines

You'll learn why the . metacharacter often "misses" newline characters and how to fix it.

By now you know that the dot (.) matches "any character"—but there's a catch. In JavaScript regular expressions, the dot has a hidden exception: it does not match newline characters (\n) by default.

Why This Matters

Imagine you're searching for any text between two markers in a multi-line string:

const text = "Start\nMiddle\nEnd";
const regex = /Start.End/;
console.log(regex.test(text)); // false — dot won't cross lines!

Even though "Start" and "End" are in the same string, the . stops at the newline. Think of the dot as a character matcher that respects line boundaries unless you tell it otherwise.

Two Solutions

Option 1: Use the s flag (dot-all mode)

The s flag makes the dot truly match any character, including \n:

const regex = /Start.+End/s;
console.log(regex.test("Start\nMiddle\nEnd")); // true

Option 2: Use [\s\S] instead of .

This character class trick says "match any whitespace OR any non-whitespace"—which covers everything:

const regex = /Start[\s\S]+End/;
console.log(regex.test("Start\nMiddle\nEnd")); // true

The [\s\S] approach works in older environments where the s flag isn't available, but modern code typically uses the s flag for clarity.

Key Takeaway: By default, the . metacharacter excludes newlines; use the s flag to match across lines, or use [\s\S] as a compatibility workaround.