Positive lookbehind

Hello. I’m failing to implement a positive lookbehind into my code because it gives me an error : invalid regexp group

function telephoneCheck(str) {
 //this works only everything except 2 
 //const regex = /^1*\s*\-*(\((?=[0-9]{3}\)))*[0-9]{3}\)*\s*\-*[0-9]{3}\s*\-*[0-9]{4}$/g
 
 //this one throws an error
 const regex = /^1*\s*\-*(\((?=[0-9]{3}\)))*[0-9]{3}(\)(?<=[0-9]{3}\())*\s*\-*[0-9]{3}\s*\-*[0-9]{4}$/

 return regex.test(str);
}

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

tests that are failing with the first line :

telephoneCheck("555)-555-5555")` should return false.;
telephoneCheck("1 555)555-5555")` should return false.

am I doing something wrong or is it compatibility issues?

Javascript supports lookahead but not lookbehind, I think. I ran into something similar. As of June, this was the answer on StackOverflow:

Well, hopefully it gets implemented soon because it’s a cool feature. Is there any other way I can match brackets only if there is an opening and closing bracket?

I have found someone who has somewhat done it but I’m having a hard time reading the code even with regex101 annotations…
Link: https://regex101.com/r/fG4rZ8/3

There is probably a more elegant solution but I think for the ( ) I used an OR expression (alternation) for the area code - one with ( ) and one without.

You’re correct, I’ve made some correction and this variant passes all the tests. :slight_smile:

const regex = /^1*\s*\-*((\([0-9]{3}\))|([0-9]{3}))\s*\-*[0-9]{3}\s*\-*[0-9]{4}$/

Way to go! :white_check_mark:

That’s using PHP’s flavor of regex. In the upper-left-hand corner, if you switch to Javascript, you’ll see that it throws an error.