JavaScript RegExp multiline Property
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.
// 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);
- regex1 matches "test" only if it appears as the entire string.
- regex2 matches "test" if it appears at the start or end of any line in a multi-line string.
Syntax:
regex.multiline
Key Points
- Read-Only: The multiline property is read-only and reflects the presence of the m flag.
- Line-Based Matching: Enables ^ and $ to work with lines in multi-line strings.
- Use Case: Ideal for parsing or validating multi-line text, such as logs or formatted data.
Real-World Examples of the multiline Property
1. Matching at Line Boundaries
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
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
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
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
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?
- Flexible Anchoring: Expands the functionality of ^ and $ anchors to work on a line-by-line basis.
- Efficient Parsing: Useful for processing multi-line logs, CSV files, or formatted text.
- Precise Validation: Enables regex-based validation of specific lines in structured data.
Conclusion
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:
- JavaScript RegExp Complete Reference
- JavaScript Cheat Sheet-A Basic guide to JavaScript
- JavaScript Tutorial