Ali
Ali

Reputation: 267187

What's the difference between the g and m modifiers in Javascript regexes?

In javascript regular expressions, you can put in a 'g' modifier for global, and 'm' for multiple. What's the difference between them, or are they the same thing?

Upvotes: 4

Views: 4458

Answers (2)

jaycethanks
jaycethanks

Reputation: 65

/m could be thought of the enhance mode modifier for /g.

Here is a sample test:

hello my darling 
you are so sweat
and hello my beauty
hello my lady
you are so kind
hello my heartbeat
you drum like a spring wind

/^hello/g : regard all content as a entirety which means it will match the entire string from the beginning "hello" to the end "wind".

/g use for match the entire string from the beginning "hello" to the end

**hello** my darling
you are so sweat
and hello my beauty
hello my lady
you are so kind
hello my heartbeat
you drum like a spring wind

/^hello/gm : will match the 1,4,6 line singly.

/gm use for match the entire string too, but it will split the entire string > by line break and it will test each line with the pattern given (line by line) > instead of just test the beginning to the end of the entire string simply.

**hello** my darling 
you are so sweat
and hello my beauty
**hello** my lady
you are so kind
**hello** my heartbeat
you drum like a spring wind

hope it can be helpful.

Upvotes: 1

Martin Ender
Martin Ender

Reputation: 44279

m does not stand for "multiple", but for "multiline". And it makes ^ and $ match at line beginnings and line endings, respectively (instead of just the beginning and ending of the string).

Well, and g really means "global", so that the regex engine continues to find further matches after the first one.

Further reading about regex modifiers.

Upvotes: 12

Related Questions