Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
49
rated 0 times [  50] [ 1]  / answers: 1 / hits: 19891  / 11 Years ago, thu, january 9, 2014, 12:00:00

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?


More From » regex

 Answers
6

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');

[#73283] Wednesday, January 8, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
judydestiniem

Total Points: 215
Total Questions: 109
Total Answers: 86

Location: Indonesia
Member since Wed, Jul 7, 2021
3 Years ago
;