Haradzieniec Haradzieniec - 3 years ago 136
Javascript Question

“combine” 2 regex with a logic or?

I have two patterns for javascript:

- string of exactly length of 10 of alphanumeric symbols.


- 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

Answer Source

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.


  • ^ - 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 string
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download