Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

regex - Why javascript string match includes undefined

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...