I want to match a sequence of initials, the whole sequence, which the second regex in the following example does for me correctly. Why is it that I need the “global” flag? The first should also match ONLY the string in its entirety, right? (because of the ^ and the $)
abc = "A.B.C."
abc.match(/^([A-Z]\.)+$/) // result: ["A.B.C.", "C."]
abc.match(/^([A-Z]\.)+$/g) // result: ["A.B.C."]
thanks!
Because the parens do not include the
+. So when you doabc.match(/^([A-Z]\.)+$/), the parens match only the first[A-Z]\..To get the match you want, you don’t need the
gflag. Just usematch[0]as your result.Working demo here: http://jsfiddle.net/jfriend00/PXF6U/
See Bergi’s answer for details on why the
gflag changes the response like you observed.