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

Anchors and Multiline Mode

How ^ and $ behave differently with the m flag, matching line starts/ends vs string ends.

Anchors and Multiline Mode

You'll learn how the ^ and $ anchors change behavior when you enable the multiline (m) flag.

By default, ^ matches the very start of the entire string, and $ matches the very end. This works perfectly for single-line validation, but what happens when your text spans multiple lines?

Default Behavior: String Boundaries Only

Without the m flag, anchors treat the entire string as one unit:

const text = "apple\nbanana\ncherry";

console.log(/^banana/.test(text));  // false — "banana" isn't at string start
console.log(/banana$/.test(text));  // false — "banana" isn't at string end
console.log(/^apple/.test(text));   // true — "apple" IS at string start

Even though "banana" starts on a new line, ^ only cares about the beginning of the whole string.

With the m Flag: Line Boundaries

Enable multiline mode with the m flag, and ^/$ suddenly recognize line breaks (\n) as boundaries:

const text = "apple\nbanana\ncherry";

console.log(/^banana/m.test(text));  // true — "banana" starts a line
console.log(/banana$/m.test(text));  // true — "banana" ends a line
console.log(/^cherry/m.test(text));  // true — "cherry" starts a line

Think of it like reading a poem: without the m flag, regex only sees the first and last words. With it, regex respects each line's beginning and ending.

Practical Use Case

Multiline mode shines when validating or processing line-by-line data:

const log = "ERROR: disk full\nINFO: started\nERROR: timeout";

// Find all lines starting with "ERROR"
const errors = log.match(/^ERROR:.*/gm);
console.log(errors);  // ["ERROR: disk full", "ERROR: timeout"]

Key Takeaway: Without the m flag, ^ and $ match string start/end only. With m, they match the start/end of each line within the string.