Artboard 16Google Sheets iconSwift icon
Published at
Updated at
Reading time
2min
This post is part of my Today I learned series in which I share all my web development learnings.

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!

MDN Compat Data (source)
Browser support info for RegExp multiline
chromechrome_androidedgefirefoxfirefox_androidsafarisafari_iossamsunginternet_androidwebview_android
111211111.51

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; so 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.

Was this TIL post helpful?
Yes? Cool! You might want to check out Web Weekly for more quick learnings. The last edition went out 4 days ago.

Related Topics

Related Articles