Home > front end >  Is there a way I can test a string using regex to be true only if ( & ) both happen at least once? T
Is there a way I can test a string using regex to be true only if ( & ) both happen at least once? T

Time:07-03

In this case it's returning true but I need it to return false. I tried adding [()]{0,1} but I think it's only referring to just one"(or)" is there a way I can do [(&)]{0,1} so that "(" and ")" both have to happen at least once. Thank you

function telephoneCheck(str) {


const regex = /^[1]{0,1}[-\s]?[(]?\d{3}[-)\s]?[\s]?[\d]{3}[-\s]?[\d]{4}$/g
return regex.test(str)
}

console.log(telephoneCheck("1 555)555-5555"));

CodePudding user response:

Given that your example involves telephone numbers, I'm going to assume that you are just looking for one pair of parentheses, and in one particular spot. You can use alternation to check for this:

/^1?[-\s]?(?:\(\d{3}\)|\d{3})[-\s]?\d{3}[-\s]?\d{4}$/g

The key is the non-capturing group starting with (?: which will pick either a sequence of three digits surrounded by parentheses or a sequence of three digits without parentheses. I also simplified the rest of your regex as you don't need to use so many brackets.

  • Related