How-to

How to Match Across Newlines in JavaScript

The dot doesn't match newlines by default. Use the s (dotall) flag, or build an explicit [\s\S] alternative for engines that predate s.

Why . doesn't match newlines

Historically, regex engines treat the dot as 'any character except newline' so that line-oriented tools (grep, sed) work sensibly on multi-line inputs. JavaScript inherited this default. <pre>.*</pre> will fail on a <pre> block that contains a newline.

Without s flag — fails mid-block

Try this
/<pre>.*</pre>/

Input

<pre>line 1 line 2</pre>

Result

No match

The s (dotall) flag

Adding the s flag makes . match ANY character including newlines. This is the cleanest modern solution. Supported in all modern JavaScript engines (Node 10+, all current browsers).

With s flag — spans newlines

Try this
/<pre>.*?</pre>/s

Input

<pre>line 1 line 2</pre>

Result

Match: whole <pre>…</pre> block

The [\s\S] workaround

Before the s flag was standardized, the common trick was [\s\S] — a character class that includes both whitespace (which includes \n) and non-whitespace. The union is 'any character.' Still useful for hand-portable regex or when you can't control engine flags.

[\s\S] alternative (no s flag needed)

Try this
/<pre>[\s\S]*?</pre>/

Input

<pre>line 1 line 2</pre>

Result

Match

Don't confuse s with m

s (dotall / single-line) makes . match newlines. m (multiline) makes ^ and $ match at line boundaries. They're independent and often used together. The naming is historically confusing — 'single-line' mode means the engine treats the input as ONE big line, which is what lets . span across \n.

Related patterns

All reference guidesOpen the RegexPro tester →