0

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.

1
  • Could you plase clarify if you need a text that can have letters and numbers, or if it must have at least a letter and at least a number? Can you please tell us if there's a limit on the size of the text (currently texts with size 30 are valid)? Commented Sep 14, 2022 at 6:41

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks for replying, my VALUE must have at least one number and letter, based on your pattern does it not work?
Oh, shoot. I'll edit the answer.
I'd also make an edit to the title of your question If you approve the pending edit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.