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}$/)
Fo
It's because your regex starts with that parenthesized group. The undefined
in the result means that nothing matched that part.
When you add the "g" suffix, the behavior of the regex code changes a little, so the return value is different. The "g" ("global") suffix causes the routine to return all the matches of the whole regex; the groups are effectively ignored in that case. For example:
"hello world! nice day today!".match(/\w+/g)
would return an array like this:
["hello", "world", "nice", "day", "today"]
You have a captured subpattern: (1[-. ]?)?
It is optional.
In this case, the option is to not match it.
Thus, it is undefined.
Try using a non-capturing subpattern: (?:1[-. ]?)?
Here is a group:
/^(1[-. ]?)?
.match
(without the /g
flag) and .exec
return groups as part of the array. If the group didn’t match, its value is set to undefined
.
Get the first element:
'(801) 555-1234'.match(/^(1[-. ]?)?\(?[0-9]{3}\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}$/)[0]
If you really, really, really want the single-element array for some reason, you can make it non-capturing:
/^(?:1[-. ]?)?
However, at that point, you have this regular expression anchored to both the start and end of the string and aren’t extracting any information. In that case, it seems like you’re really looking for RegExp.prototype.test
:
var PHONE_NUMBER = /^(1[-. ]?)?\(?[0-9]{3}\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}$/;
var isValid = PHONE_NUMBER.test('(801) 555-1234');
In Your Regex (1[-. ]?)?
indicates
NODE EXPLANATION
--------------------------------------------------------------------------------
( group and capture to \1 (optional
(matching the most amount possible)):
--------------------------------------------------------------------------------
1 '1'
--------------------------------------------------------------------------------
[-. ]? any character of: '-', '.', ' '
(optional (matching the most amount
possible))
--------------------------------------------------------------------------------
)? end of \1 (NOTE: because you are using a
quantifier on this capture, only the LAST
repetition of the captured pattern will be
stored in \1)
And Try (?:1[-. ]?)?
NODE EXPLANATION
--------------------------------------------------------------------------------
(?: group, but do not capture (optional
(matching the most amount possible)):
--------------------------------------------------------------------------------
1 '1'
--------------------------------------------------------------------------------
[-. ]? any character of: '-', '.', ' '
(optional (matching the most amount
possible))
--------------------------------------------------------------------------------
)? end of grouping