JavaScript RegExp multiline
: Multiline Flag (m)
The multiline
property of the JavaScript RegExp
object indicates whether the m
flag is used in the regular expression. The m
flag enables multiline matching, allowing the ^
and $
anchors to match the start and end of each line within a multiline string, rather than just the start and end of the entire string. This is particularly useful when working with text containing newline characters.
Purpose of the multiline
Property
The multiline
property is used to determine if a regular expression is configured for multiline matching. This impacts how the ^
(start of line) and $
(end of line) anchors behave. When multiline
is true
, these anchors match at the beginning and end of each line. When multiline
is false
, they only match at the beginning and end of the entire input string.
Syntax
regexObj.multiline;
Return Value: A boolean value. Returns true
if the “m” flag was used; otherwise, false
.
Key Considerations
- The
multiline
property is read-only. - It reflects whether the
m
flag was used when creating the regular expression. - It affects the behavior of
^
and$
anchors in the regex pattern.
Examples
Basic Example: Checking the multiline
Property
This example demonstrates how to check the multiline
property of a regular expression.
const regex1 = /hello/m;
const regex2 = /world/;
console.log(regex1.multiline); // Output: true
console.log(regex2.multiline); // Output: false
Output:
true
false
Using the multiline
Flag for Start and End of Line Anchors
This example shows how the m
flag changes the behavior of the ^
and $
anchors.
const multilineString = "first line\nsecond line\nthird line";
const regexMultiline = /^second/m;
const regexSingleline = /^second/;
console.log(regexMultiline.test(multilineString)); // Output: true
console.log(regexSingleline.test(multilineString)); // Output: false
Output:
true
false
In this example, the regexMultiline
with the m
flag correctly matches “second” at the start of the second line. Without the m
flag, regexSingleline
fails to match because “second” is not at the start of the entire string.
Extracting Lines Using the multiline
Flag
This example demonstrates how to extract all lines that start with a specific word using the multiline
flag and the ^
anchor.
const text_extract = `Begin: Line one
Another: Line two
Begin: Line three`;
const regex_extract = /^Begin: .*/gm;
const matches_extract = text_extract.match(regex_extract);
console.log(matches_extract);
Output:
[ 'Begin: Line one', 'Begin: Line three' ]
Here, the gm
flags are used to perform a global (find all matches) and multiline search. The regex matches any line that starts with “Begin:”.
Replacing Lines Using the multiline
Flag
This example demonstrates how to replace lines that match a certain pattern using the multiline
flag.
const text_replace = `Line one: apple
Line two: banana
Line three: apple`;
const regex_replace = /^Line .* apple$/gm;
const replacedText_replace = text_replace.replace(regex_replace, "Replaced line");
console.log(replacedText_replace);
Output:
Replaced line
Line two: banana
Replaced line
In this example, the gm
flags ensure that all lines ending with “apple” are replaced, not just the first one.
Complex Example: Validating Multiline Input
This example demonstrates a more complex use case where you need to validate each line of a multiline input to ensure it meets specific criteria.
function validateMultilineInput(input) {
const lineRegex = /^[A-Z][a-z]+: \d+$/m;
const lines = input.split('\n');
let isValid = true;
for (const line of lines) {
if (!lineRegex.test(line)) {
isValid = false;
break;
}
}
return isValid;
}
const valid_input = `Name: 123
Age: 456
City: 789`;
const invalid_input = `Name: 123
Age: abc
City: 789`;
console.log("Valid input: ", validateMultilineInput(valid_input));
console.log("Invalid input: ", validateMultilineInput(invalid_input));
Output:
Valid input: true
Invalid input: false
This function checks if each line of the input starts with a capital letter followed by lowercase letters, a colon, and then a number. The multiline
flag is not directly used in the test
method here because we are splitting the input into lines and testing each line individually. But the initial regex is defined with m
flag so it is available in the lineRegex
object.
Real-World Applications
The multiline
flag and property are useful in various real-world scenarios:
- Text Editors and IDEs: Implementing search and replace functionalities across multiple lines.
- Log Analysis: Parsing and extracting information from multiline log files.
- Form Validation: Validating multiline text inputs, such as addresses or descriptions.
- Code Parsing: Analyzing and manipulating code blocks in programming languages.
- Data Extraction: Extracting data from text files with multiline records.
Key Takeaways
- The
multiline
property reflects whether them
flag is used in a regular expression. - The
m
flag enables multiline matching, affecting the behavior of^
and$
anchors. - Multiline matching is essential when working with text containing newline characters and when you need to match the start or end of individual lines.
- Understanding and using the
multiline
property and flag correctly is crucial for effective regular expression use in JavaScript.