Multiline Regular Expressions in Javascript

Comments

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

The problem

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

1
2
3
4
5
6
7
"line 0\nline1".match(/\d.line/)
// null

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

The solution

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

1
2
3
4
5
6
7
8
9
10
"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

Comments