Regex for youtube URL

后端 未结 8 1349
囚心锁ツ
囚心锁ツ 2020-11-28 09:12

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

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


        
相关标签:
8条回答
  • 2020-11-28 09:58

    Here's a regex I use to match and capture the important bits of YouTube URLs with video codes:

    ^((?:https?:)?\/\/)?((?:www|m)\.)?((?:youtube\.com|youtu.be))(\/(?:[\w\-]+\?v=|embed\/|v\/)?)([\w\-]+)(\S+)?$
    

    Works with the following URLs:

    https://www.youtube.com/watch?v=DFYRQ_zQ-gk&feature=featured
    https://www.youtube.com/watch?v=DFYRQ_zQ-gk
    http://www.youtube.com/watch?v=DFYRQ_zQ-gk
    //www.youtube.com/watch?v=DFYRQ_zQ-gk
    www.youtube.com/watch?v=DFYRQ_zQ-gk
    https://youtube.com/watch?v=DFYRQ_zQ-gk
    http://youtube.com/watch?v=DFYRQ_zQ-gk
    //youtube.com/watch?v=DFYRQ_zQ-gk
    youtube.com/watch?v=DFYRQ_zQ-gk
    
    https://m.youtube.com/watch?v=DFYRQ_zQ-gk
    http://m.youtube.com/watch?v=DFYRQ_zQ-gk
    //m.youtube.com/watch?v=DFYRQ_zQ-gk
    m.youtube.com/watch?v=DFYRQ_zQ-gk
    
    https://www.youtube.com/v/DFYRQ_zQ-gk?fs=1&hl=en_US
    http://www.youtube.com/v/DFYRQ_zQ-gk?fs=1&hl=en_US
    //www.youtube.com/v/DFYRQ_zQ-gk?fs=1&hl=en_US
    www.youtube.com/v/DFYRQ_zQ-gk?fs=1&hl=en_US
    youtube.com/v/DFYRQ_zQ-gk?fs=1&hl=en_US
    
    https://www.youtube.com/embed/DFYRQ_zQ-gk?autoplay=1
    https://www.youtube.com/embed/DFYRQ_zQ-gk
    http://www.youtube.com/embed/DFYRQ_zQ-gk
    //www.youtube.com/embed/DFYRQ_zQ-gk
    www.youtube.com/embed/DFYRQ_zQ-gk
    https://youtube.com/embed/DFYRQ_zQ-gk
    http://youtube.com/embed/DFYRQ_zQ-gk
    //youtube.com/embed/DFYRQ_zQ-gk
    youtube.com/embed/DFYRQ_zQ-gk
    
    https://youtu.be/DFYRQ_zQ-gk?t=120
    https://youtu.be/DFYRQ_zQ-gk
    http://youtu.be/DFYRQ_zQ-gk
    //youtu.be/DFYRQ_zQ-gk
    youtu.be/DFYRQ_zQ-gk
    
    https://www.youtube.com/HamdiKickProduction?v=DFYRQ_zQ-gk
    

    The captured groups are:

    1. protocol
    2. subdomain
    3. domain
    4. path
    5. video code
    6. query string

    http://regexr.com/3dj5t

    0 讨论(0)
  • 2020-11-28 09:59

    Format for YouTube videos has changed. This regex works for all cases:

    ^(http(s)??\:\/\/)?(www\.)?((youtube\.com\/watch\?v=)|(youtu.be\/))([a-zA-Z0-9\-_])+
    

    Tests here.

    0 讨论(0)
提交回复
热议问题