Royi Namir
Royi Namir

Reputation: 148644

Does Regex's [m] flag must come with [g] flag?

I read on MDN that :

m flag  / multiline : 

Treat beginning and end characters (^ and $) as working over multiple lines

So I made a test (http://regexr.com?374jj) :

I have this simple regex :

^[\s\S]{3}

If I dont check global and multiline :

enter image description here

If I check only global :

enter image description here

If I check both global + multiline :

enter image description here

So it seems that multiline works only with the global flag.

Does my observation/conclusions are right ? Does multi line should be always with global ?

Upvotes: 2

Views: 177

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1075059

m doesn't require or imply g, no. Consider:

"foo\nbar".match(/^bar/)   // `null`

vs.

"foo\nbar".match(/^bar/m)  // ["bar"]

With the m flag, ^bar matches because the ^ matches at the beginning of the line. Without it, there is no match, because ^ doesn't match at the beginning of the input string. The m flag has the analogous effect on the end-of-(line|input) anchor $ as well.

The g flag comes into play when you need to do the match more than once. Consider this difference, for instance:

"foo\nbar\nfoo\nbar".replace(/^bar/m, "BAZ")

...which gives us:

foo
BAZ
foo
bar

Note that the second match wasn't replaced. Compare with the result if we add the g flag:

"foo\nbar\nfoo\nbar".replace(/^bar/mg, "BAZ")

...which gives us:

foo
BAZ
foo
BAZ

Note that all matches were replaced.

Upvotes: 3

plalx
plalx

Reputation: 43728

Well, it depends what you are trying to achieve. Without the global flag, you will only get the first match. Without the multiline flag, only the first line will be considered.

Upvotes: 1

Related Questions