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

Multiline Mode with 'm'

How the 'm' flag affects ^ and $ anchors to match line boundaries instead of string boundaries.

Multiline Mode with 'm'

You'll learn how the m flag changes ^ and $ behavior to match at every line break, not just at the start and end of the entire string.

The Core Idea

By default, the ^ and $ anchors match the very beginning and very end of the entire string. When you add the multiline flag (m), these anchors gain new powers: ^ matches right after every newline character (\n), and $ matches right before every newline. This lets you work with multi-line text line-by-line.

Without the 'm' Flag

const text = "apple\nbanana\napricot";
const pattern = /^a/;  // No 'm' flag

console.log(pattern.test(text));  // true (matches "apple" at string start)

Only the very first character of the entire string is checked.

With the 'm' Flag

const text = "apple\nbanana\napricot";
const pattern = /^a/m;  // Multiline mode enabled

const matches = text.match(/^a/gm);
console.log(matches);  // ["a", "a"] (both "apple" and "apricot")

Now ^a matches at the start of the string and after the \n before "apricot".

The '$' Anchor in Multiline Mode

const text = "apple\nbanana\napple";
const pattern = /e$/gm;

console.log(text.match(pattern));  // ["e", "e"] (end of "apple" lines)

Without m, only the final "e" in the entire string would match.

Key Takeaway: The m flag transforms ^ and $ from string-boundary anchors into line-boundary anchors, making them match after and before newlines within your text.