Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Multiple RegEx not working with conditions

I’m trying to use two RegEx.test() methods with Logical AND in a conditional block, however, not getting expected result.

const mobileRegEx = /[0][4-5][0-9]{8}/g;
const firstPhone = '0432779680';
const secondPhone = '0543000987';


if(mobileRegEx.test(firstPhone)  &&  mobileRegEx.test(secondPhone)){
    console.log(firstPhone, secondPhone); /* expecting this to be executed but it is not */
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

A regular expression with the g (global) flag keeps track of the position of the last match, and keeps searching from the next position.

So this means that the first match will return the position on the first number, and then the second match will fail because instead of restarting from the start it will start from the position of the first match and miss.

The fix is to simply remove the g from your original expression like this

/[0][4-5][0-9]{8}/;

However, I also see that your expression might give false positives. For example, if you add random characters before and after the actual number, it will still match.

E.g.

firstPhone = 'WRONG0432779680WRONG';

Will still return true. If you’re using this for validating a phone number format, you need to restrict the regex to the whole string passed. You can do so by using ^ at the beginning and $ at the end, to say this is the whole string.

So the regex should look like

const mobileRegEx = /^[0][4-5][0-9]{8}$/;

Here’s the final code

const mobileRegEx = /^[0][4-5][0-9]{8}$/;
const firstPhone = '0432779680';
const secondPhone = '0543000987';
if(mobileRegEx.test(firstPhone)  &&  mobileRegEx.test(secondPhone)){
    console.log(firstPhone, secondPhone);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading