Reputation: 9338
I have two patterns for javascript:
/^[A-z0-9]{10}$/
- string of exactly length of 10 of alphanumeric symbols.
and
/^\d+$/
- any number of at least length of one.
How to make the expression of OR string of 10 or any number?
var pattern = /^([A-z0-9]{10})|(\d+)$/;
doesn't work by some reason. It passes at lest
pattern.test("123kjhkjhkj33f"); // true
which is not number and not of length of 10 for A-z0-9
string.
Upvotes: 1
Views: 76
Reputation: 627180
Note that your ^([A-z0-9]{10})|(\d+)$
pattern matches 10 chars from the A-z0-9
ranges at the start of the string (the ^
only modifies the ([A-z0-9]{10})
part (the first alternative branch), or (|
) 1 or more digits at the end of the stirng with (\d+)$
(the $
only modifies the (\d+)
branch pattern.
Also note that the A-z
is a typo, [A-z]
does not only match ASCII letters.
You need to fix it as follows:
var pattern = /^(?:[A-Za-z0-9]{10}|\d+)$/;
or with the i
modifier:
var pattern = /^(?:[a-z0-9]{10}|\d+)$/i;
See the regex demo.
Note that grouping is important here: the (?:...|...)
makes the anchors apply to each of them appropriately.
Details
^
- start of string(?:
- a non-capturing alternation group:
[A-Za-z0-9]{10}
- 10 alphanumeric chars|
- or\d+
- 1 or more digits)
- end of the grouping construct$
- end of stringUpvotes: 3