Multiline regular expressions in Javascript

regexp, javascript

There are no flags to match multi-line text is in JS. But it can be done with a character class.

In javascript, newlines are not matched by .

In both the cases below we expect \d.line to match 0\nline but it doesn't work - because newlines are not matched by the . character class.

"line 0\nline1".match(/\d.line/)
// null

// ES6
`line 0
line1`.match(/\d.line/)
// null

[^] matches newlines in javascript regular expressions

Use the [^] character class, which is equivalent to . but with the newline added in

"line 0\nline1".match(/\d[^]line/)
// ["0
// line"]


// ES6
`line 0
line1`.match(/\d[^]line/)
// ["0
// line"]

For more info, visit the relevant MDN page