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

Multiline Mode and Line Boundaries

Understand how the 'm' flag changes ^ and $ to match line breaks within strings, not just string boundaries.

Multiline Mode and Line Boundaries

You'll learn how the m flag transforms ^ and $ from string boundaries into line boundaries within multiline text.

The Core Idea

By default, ^ matches only the very start of the entire string, and $ matches only the very end. But when you add the multiline flag (m), these anchors change behavior: they now match at every line break (\n) within the string, not just at the absolute beginning and end.

Think of it like switching from "chapter mode" to "paragraph mode" in a book. Without m, you're only detecting the first and last page of the entire book. With m, you can detect the start and end of every paragraph.

Without the m Flag

const text = "hello\nworld\ntest";
const regex = /^world/;

console.log(regex.test(text)); // false
// "world" isn't at the START of the whole string

With the m Flag

const text = "hello\nworld\ntest";
const regexMultiline = /^world/m;

console.log(regexMultiline.test(text)); // true
// "world" IS at the start of a line (after \n)

How It Works

  • /^world/m matches "world" if it appears at the start of any line
  • /test$/m matches "test" if it appears at the end of any line
  • Without m, they'd only match at absolute string boundaries

Practical Use

Perfect for processing logs, CSV data, or any multi-line text where you need to validate or extract content line-by-line using pattern matching.

Key Takeaway: The multiline flag (m) makes ^ and $ match at line breaks (\n), not just string boundaries, enabling line-by-line pattern matching within multiline strings.