How to perform Multiline matching with JavaScript RegExp?

To perform multiline matching in JavaScript, use the m flag with regular expressions. This flag makes ^ and $ anchors match the beginning and end of each line, not just the entire string.

Syntax

/pattern/m
new RegExp("pattern", "m")

How the m Flag Works

Without the m flag, ^ matches only the start of the string and $ matches only the end. With the m flag, they match line boundaries created by
(newline) characters.

Example: Basic Multiline Matching

<html>
   <head>
      <title>JavaScript Regular Expression</title>
   </head>

   <body>
      <script>
         var myStr = "Welcome\ning!";
         var reg = /^ing/m;
         var match = myStr.match(reg);
         
         document.write("Match found: " + match);
      </script>
   </body>
</html>
Match found: ing

Comparison: With and Without m Flag

let text = "First line\nSecond line\nThird line";

// Without m flag - only matches start/end of entire string
let withoutM = text.match(/^Second/);
console.log("Without m flag:", withoutM);

// With m flag - matches start/end of each line
let withM = text.match(/^Second/m);
console.log("With m flag:", withM);
Without m flag: null
With m flag: Second

Finding All Line Beginnings

let multilineText = "apple\nbanana\ncherry";

// Find all words at line beginnings
let matches = multilineText.match(/^\w+/gm);
console.log("All line beginnings:", matches);
All line beginnings: ["apple", "banana", "cherry"]

Comparison Table

Flag ^ Matches $ Matches Use Case
No flag Start of string only End of string only Single-line text
m Start of each line End of each line Multiline text

Conclusion

The m flag enables line-by-line pattern matching in multiline strings. Use it when you need to match patterns at the beginning or end of individual lines rather than the entire string.

Updated on: 2026-03-15T23:18:59+05:30

690 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements