how to get YouTube video id from image thumbnail s

2019-01-29 08:20发布

问题:

So if the image tag is

<img src="http://i1.ytimg.com/vi/LL0Y4MZ45bo/0.jpg" class="youtubeimg"></img>

I don't know how to extract the YouTube video id (LL0Y4MZ45bo) from the thumbnail image src and then apply it to an iframe.

currently i have 100% working, which applys the src to the iframe. but what i dont know how to do is get the id from the img tags in this case LL0Y4MZ45bo and add it to the youtube embed src http://www.youtube.com/embed/LL0Y4MZ45bo

<iframe src="" class="youtubeiframe"></iframe>

<script>
$(".youtubeiframe").attr({ 
  src: "http://www.youtube.com/embed/VIDEO-ID-EXTRACTED-FROM-THUMBNAIL-SRC",
});
</script>

so how can I extract id from the img and apply to iframe src?

回答1:

This extracts the YouTube ID using a Regular Expression, I made the assumption that it would be a minimum of eleven characters as the first YouTube Video ID has 11.

<img src="http://i1.ytimg.com/vi/LL0Y4MZ45bo/0.jpg" class="youtubeimg"></img>
<iframe src="" class="youtubeiframe"></iframe>

<script>
    $(function (){
        var youtubeid = $(".youtubeimg").attr("src").match(/[\w\-]{11,}/)[0];
        $(".youtubeiframe").attr({ 
              src: "http://www.youtube.com/embed/" + youtubeid,
        });
    });
</script>

This works, however the YouTube Player API may provide you with a more stable solution to loading that iFrame, in the future once it becomes stable I would recommend the YouTube iFrame API



回答2:

I think you can do this more easily if you'll start to study the YouTube API.



回答3:

Make the URL as an array and than take the second to last part. For example this also works with CSS background-image.

id = $('div').attr('style').split('/');
id = id[id.length-2];
alert("YouTube ID: " + id);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="background-image:url('https://img.youtube.com/vi/MHUOty8-Ty0/0.jpg');"></div>

https://jsfiddle.net/Wobbo/wfyL1hem/7/