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

The Multiline Flag (m)

How m affects ^ and $ to match line boundaries instead of just string boundaries.

The Multiline Flag (m)

You'll learn how the m flag changes the way ^ and $ anchors work, making them match line boundaries instead of only string boundaries.

What Does the Multiline Flag Do?

By default, the ^ anchor matches the start of the entire string, and the $ anchor matches the end of the entire string. When you add the m flag to a regular expression, these anchors change behavior: ^ now matches the start of any line within the string, and $ matches the end of any line.

Think of it this way: Without m, your regex treats the whole string as one continuous block. With m, it recognizes newline characters (\n) as creating separate "lines," and ^ and $ can anchor to those internal line breaks.

How to Use It

const multilineText = "apple\nbanana\ncherry";

// Without m flag: ^ only matches start of entire string
const withoutM = /^banana/;
console.log(withoutM.test(multilineText)); // false

// With m flag: ^ matches start of any line
const withM = /^banana/m;
console.log(withM.test(multilineText)); // true

// With m flag: $ matches end of any line
const endPattern = /apple$/m;
console.log(endPattern.test(multilineText)); // true

In the example above, "banana" isn't at the start of the string, but it is at the start of its own line (after the \n). The m flag makes ^ recognize that.

When You Need It

Use the multiline flag when processing text with multiple lines—like log files, CSV data, or user input with line breaks—and you need to match patterns at the beginning or end of individual lines rather than just the whole string.

Key Takeaway: The m flag makes ^ and $ anchors match the start and end of each line (separated by newlines) instead of only the start and end of the entire string.