Whats the difference between | and || in javascript?

Tell us what’s happening:
look at my code, and you can see that it outputs the differences aanswers for the differences using of | or ||!

Your code so far


function telephoneCheck(str) {
var regex = 
/^(1\s?)?(\(\d{3}\)||\d{3})[\s\-]?(\d{3})[\s\-]?\d{4}$/;
var regex2 = 
/^(1\s?)?(\(\d{3}\)|\d{3})[\s\-]?\d{3}[\s\-]?\d{4}$/;
console.log(regex.test(str));
console.log(regex2.test(str));
}

telephoneCheck("555-5555");

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36.

Challenge: Telephone Number Validator

Link to the challenge:

I think this is invalid syntax for JS flavoured regex.

the | operator, or ‘alternator’ in regex, matches one or the other thing. There is no || in JS regex - you may be confusing it with the || OR from JS (not regex).

If it were valid, /a||b/ would get parsed as something like match a or blank or b, so it returns true in your case (matching on the blank), if that makes sense?

I only suspect this to be the case though…regex is the dark arts!

You can try something like https://regex101.com which is a great tool for putting regex strings and tests together (remember to put in ECMAscript mode - different languages have different flavours of regex)

1 Like

Oh, i got it! Thanks you so much bro, and i agree with you. I do think that regex is a dark art too XD

1 Like