I have a regex that is more or less used like this:
'(801) 555-1234'.match(/^(1[-. ]?)?(?[0-9]{3})?[-. ]?[0-9]{3}[-. ]?[0-9]{4}$/)
For some reason this returns
["(801) 555-1234", undefined]
If I add the global flag to the regex (e.g. ...{4}$/g
), the undefined value drops out and I get
["(801) 555-1234"]
I'd prefer not to use the g flag if it's not necessary (which it would seem to me it's not, since the regex begins with ^ and ends with $).
P.S. ignore the quality of the regex for it's purpose of matching phone numbers. It may not be ideal, but is from code I'm maintaining. Mostly I'm interested in the ^...$ and the presence/absence of the flag and the undefined value.
Why is undefined
showing up, and why does the flag make the difference?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…