Last Updated : 11 Jul, 2025
The multiline property of a JavaScript regular expression indicates whether the m (multiline) flag is enabled. When enabled, the ^ and $ anchors match the start and end of each line within a string, rather than the entire string.
JavaScript
// Regular expression without 'm' flag
let regex1 = /^test$/;
console.log(regex1.multiline);
// Regular expression with 'm' flag
let regex2 = /^test$/m;
console.log(regex2.multiline);
regex.multilineKey Points
let s = "hello\ntest\nworld";
let regex = /^test$/m;
console.log(regex.test(s));
The m flag allows the ^ and $ anchors to match "test" as a separate line in the string.
2. Retrieving Matches from Multi-Line Text JavaScript
let s = "error: 404\nsuccess: 200\nerror: 500";
let regex = /^error: \d+$/gm;
let matches = s.match(regex);
console.log(matches);
The m flag ensures that each line is treated as a separate unit for pattern matching.
3. Validating Multi-Line Input JavaScript
let input = "Name: John\nAge: 30\nLocation: NY";
let regex = /^Age: \d+$/m;
console.log(regex.test(input));
The m flag helps validate the "Age" field, regardless of its position in the multi-line input.
4. Counting Lines with a Specific Pattern JavaScript
let logs = "INFO: Started\nERROR: Missing file\nINFO: Completed";
let regex = /^ERROR:/gm;
let count = 0;
while (regex.exec(logs)) {
count++;
}
console.log(`Error count: ${count}`);
The m flag enables line-based pattern matching for structured log files.
5. Replacing Lines with a Specific Pattern JavaScript
let text = "Task 1: Incomplete\nTask 2: Complete\nTask 3: Incomplete";
let regex = /^Task \d+: Incomplete$/gm;
let updatedText = text.replace(regex, "Task: Updated");
console.log(updatedText);
The m flag ensures that each line matching the pattern is replaced independently.
Why Use the multiline Property?The multiline property is a powerful feature for handling multi-line strings in JavaScript, making it a valuable tool for tasks that involve parsing, validating, or manipulating text data with line-specific requirements.
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