Last Updated : 11 Jul, 2025
The m modifier in JavaScript regular expressions stands for "multiline". It alters the behavior of the ^ (caret) and $ (dollar) anchors, allowing them to match the start or end of any line in a multiline string, rather than just the start or end of the entire string.
JavaScript
let regex = /^hello/m;
let str = "world\nhello\nJavaScript";
let match = str.match(regex);
console.log(match);
[ 'hello', index: 6, input: 'world\nhello\nJavaScript', groups: undefined ]
The ^hello pattern matches "hello" at the beginning of the second line because the m modifier treats each line separately.
Syntax:let regex = /pattern/m;
let regex = /^error/m;
let str = "info: everything is fine\nerror: something went wrong\ninfo: all good";
let matches = str.match(regex);
console.log(matches);
[ 'error', index: 25, input: 'info: everything is fine\nerror: something went wrong\ninfo: all good', groups: undefined ]
The ^error pattern matches "error" at the beginning of the second line.
2. Matching the End of Any Line JavaScript
let regex = /fine$/m;
let str = "info: everything is fine\nerror: something went wrong";
let match = str.match(regex);
console.log(match);
[ 'fine', index: 20, input: 'info: everything is fine\nerror: something went wrong', groups: undefined ]
The $fine pattern matches "fine" at the end of the first line.
3. Finding All Matches Across Lines JavaScript
let regex = /^\w+/gm;
let str = "line1\nline2\nline3";
let matches = str.match(regex);
console.log(matches);
[ 'line1', 'line2', 'line3' ]
The ^\w+ pattern matches the first word in each line because of the m modifier.
4. Validating Multiline Input JavaScript
let regex = /^(error|info):/m;
let str = "error: this is an error\ninfo: this is information";
if (regex.test(str)) {
console.log("Valid log format.");
} else {
console.log("Invalid log format.");
}
The ^(error|info): pattern ensures each line begins with "error:" or "info:".
5. Removing Blank Lines JavaScript
let regex = /^\s*$/gm;
let str = "line1\n\nline2\n\n";
let cleaned = str.replace(regex, "");
console.log(cleaned);
The pattern ^\s*$ matches empty lines in the string, and the m modifier ensures all lines are checked.
Common Patterns Using m/^word/m
/^\s*$/m
/\.$/m
/^(info|error|debug):/m
str.split(/\r?\n/);Why Use the m Modifier?
The m modifier is an invaluable tool when working with multi-line strings in JavaScript. It ensures efficient line-by-line pattern matching and processing.
Recommended Links:RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4