javascripthtmlurlyoutubeyoutube-iframe-api

Differentiate between youTube URLs and the file names of embedded MP4s?


I want to, in my init() function, check to see if the video is either a youtube URL or a file name.

Does this seem suitable or is there some kind of edge case I might be missing?

    function init(){
        playerSource = Document.getElementById('vid').src;
        if ( playerSource.includes("https://www.youtube") ){
            //Call to function that begins setting up YT iFrame API
        }
    }

Thanks in advance!


Solution

  • You can validate the youtube URL using below regex.

    regExp = /^(?:https?:\/\/)?(?:www\.)?(?:m\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/
    

    Youtube has different url forms depending upon where you are taking from

    Normal Url

    https://www.youtube.com/watch?v=12345678901
    

    Share Url

    https://youtu.be/12345678901
    

    Share Url with start time

    https://youtu.be/12345678901?t=6
    

    Mobile browser url

    https://m.youtube.com/watch?v=12345678901&list=RD12345678901&start_radio=1
    

    Long url

    https://www.youtube.com/watch?v=12345678901&list=RD12345678901&start_radio=1&rv=smKgVuS
    

    Long url with start time

    https://www.youtube.com/watch?v=12345678901&list=RD12345678901&start_radio=1&rv=12345678901&t=38
    

    You can check these URL validation below https://regex101.com/r/7a1lGH/1