Search code examples
regexyoutube

Regex for youtube URL


I am using the following regex for validating youtube video share url's.

var valid = /^(http\:\/\/)?(youtube\.com|youtu\.be)+$/;
alert(valid.test(url));
return false;

I want the regex to support the following URL formats:

http://youtu.be/cCnrX1w5luM  
http://youtube/cCnrX1w5luM  
www.youtube.com/cCnrX1w5luM  
youtube/cCnrX1w5luM  
youtu.be/cCnrX1w5luM   

I tried different regex but I am not getting a suitable one for share links. Can anyone help me to solve this.


Solution

    • You're missing www in your regex
    • The second \. should optional if you want to match both youtu.be and youtube (but I didn't change this since just youtube isn't actually a valid domain - see note below)
    • + in your regex allows for one or more of (youtube\.com|youtu\.be), not one or more wild-cards.
      You need to use a . to indicate a wild-card, and + to indicate you want one or more of them.

    Try:

    ^(https?\:\/\/)?(www\.youtube\.com|youtu\.be)\/.+$
    

    Live demo.

    If you want it to match URLs with or without the www., just make it optional:

    ^(https?\:\/\/)?((www\.)?youtube\.com|youtu\.be)\/.+$
    

    Live demo.

    Invalid alternatives:

    If you want www.youtu.be/... to also match (at the time of writing, this doesn't appear to be a valid URL format), put the optional www. outside the brackets:

    ^(https?\:\/\/)?(www\.)?(youtube\.com|youtu\.be)\/.+$
    

    youtube/cCnrX1w5luM (with or without http://) isn't a valid URL, but the question explicitly mentions that the regex should support that. To include this, replace youtu\.be with youtu\.?be in any regex above. Live demo.