Regex for youtube URL

后端 未结 8 1405
囚心锁ツ
囚心锁ツ 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:53

    • You're missing www in your regex
    • The second \. should optional (since both youtu.be and youtube are valid)
    • + 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)\/.+$
    

    Test.

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

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

    If you want www.youtu.be/... to also match, put the optional www. outside the brackets:

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

提交回复
热议问题