Home > Mobile >  How can I combine multi regex together in javascript?
How can I combine multi regex together in javascript?

Time:09-15

How can I combine multi regex together in javascript?

I have 3 regexes and want to combine them together.

const VALUE="qwer1234"

const pattern1 = /^.{5,20}/
const pattern2 = /[a-zA-Z]/
const pattern3 = /\d/

if(pattern1.test(VALUE) && pattern2.test(VALUE) && pattern3.test(VALUE)){
  // do something...
}

I tried and could not solve it. thanks in advance.

CodePudding user response:

You can write more complex patterns. Like:

const pattern = /^(?=.*?[a-zA-Z])(?=.*?[0-9])[a-zA-Z0-9]{5,20}$/

^ Start of the string

?=.*?[a-zA-Z] Atleast one letter

?=.*?[0-9] Atteast one digit

[a-zA-Z0-9]{5,20} Between 5 to 20 letters or digits. You can replace this part with .{5,20} if you want to allow any other characters too.

$ End of the string

I think what you were trying to match was a string with 5 to 20 lowercase and uppercase characters and digits. If so instead of writing it in different patterns you need to find a way to describe every condition in one pattern. I recommend using a tool like: https://regex101.com/ to speed up testing different patterns.

  • Related