This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis
Today I learned that JavaScript regular expressions support the multiline
flag (m
), and it's nothing new and shiny... The RegExp features is supported for years!
To see how multiline
regular expressions work, let's look at an example that includes the caret (^
) anchor.
const winners = `1st place: Winnie
2nd place: Piglet
3rd place: Eeyore`;
// Match strings that:
// - start with a digit (^\d)
// - are followed by any sequence of characters (.+?)
// - include a colon (:)
// - and test for all possible matches (g)
winners.match(/^\d.+?:/g); // ["1st:"]
The regular expression /^\d.+?:/
matches only 1st:
. ^
indicates that you want to match a pattern at the beginning of a string. There's only one string beginning; there can only be one match. That's reasonable. 😉
But what if you want to match 1st:
, 2nd:
and 3rd:
?
This situation is when multiline
helps.
const winners = `1st place: Jane
2nd place: Joe
3rd place: Stefan`;
// Match strings that:
// - start lines with a digit (^\d)
// - are followed by any sequence of characters (.+?)
// - include a colon (:)
// - consider multiple lines (m)
// - and test for all possible matches (g)
winners.match(/^\d.+?:/gm); // ["1st:", "2nd:", "3rd:"]
The m
flag changes the meaning of ^
from "start of the string" to "start of a new line". This behavior can also be applied for $
.
const winners = `1st place
2nd place
3rd place`;
// Match strings that:
// - include a digit (\d)
// - are followed by any sequence of characters (.+?)
// - to the end of the string ($)
// - and test for all possible matches (g)
winners.match(/\d.+?$/g);
// [ "3rd place" ]
// Match strings that:
// - include a digit (\d)
// - are followed by any sequence of characters (.+?)
// - to the end of the line ($)
// - and test for all possible matches (g)
winners.match(/\d.+?$/gm);
// [ "1st place", "2nd place", "3rd place" ]
And here's a last fun fact: multiline
also considers \n
(line feed), \r
(carriage return) and other line breaks such as \u2028
(line separator) and \u2029
(paragraph separator).
That's pretty cool stuff! If you want to learn more, here's the MDN page for multiline
.
Reply to Stefan
This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis
Stefan Judis | Sciencx (2022-01-18T23:00:00+00:00) Multiline mode in JavaScript regular expressions (#tilPost). Retrieved from https://www.scien.cx/2022/01/18/multiline-mode-in-javascript-regular-expressions-tilpost/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.