DEV Community

GoToolsOnline
GoToolsOnline

Posted on

The m and s regex flags, explained with one example

Two JavaScript regex flags get mixed up constantly: m (multiline) and s (dotAll). They sound related, but they change completely different things.

Take this text:

error: disk full
info: retrying
error: timeout
Enter fullscreen mode Exit fullscreen mode

m changes what ^ and $ mean

Without m, ^ matches only at the very start of the whole string and $ only at the very end.

const log = "error: disk full\ninfo: retrying\nerror: timeout";
log.match(/^error: .*$/g);   // null — $ can't match before the \n
log.match(/^error: .*$/gm);  // ["error: disk full", "error: timeout"]
Enter fullscreen mode Exit fullscreen mode

With m, ^ and $ also match at the start and end of every line. Use it whenever you're matching line by line in a multi-line string.

s changes what . means

By default . matches any character except a line break. With s, it matches line breaks too.

log.match(/disk.*timeout/);   // null — . stops at the first \n
log.match(/disk.*timeout/s);  // ["disk full\ninfo: retrying\nerror: timeout"]
Enter fullscreen mode Exit fullscreen mode

Use s when a match genuinely spans lines, like a block between two markers. Combine it with a lazy quantifier (.*?) so it stops at the first end marker instead of the last.

Quick rule

  • Matching per line? Add m.
  • Matching across lines? Add s.
  • Neither flag touches \n in your pattern: \n always matches a newline.

Before shipping a pattern, test it on lines that should match and lines that shouldn't.


Disclosure: I run GoToolsOnline. Its free regex tester highlights JavaScript matches as you type and lets you toggle the i, m, s and u flags to see the difference live.

Top comments (0)