I'd like to loop through list items onload
and detect whether or not they have a YouTube URL and use the video id from the URL in an iframe. This is what I've done so far but it's not working:
$('li').each(function() {
var url = $(this).text();
if (url != undefined || url != '') {
var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=|\?v=)([^#\&\?]*).*/;
var match = url.match(regExp);
if (match && match[2].length == 11) {
// Do anything for being valid
// if need to change the url to embed url then use below line
$(this).find('.videoObject').attr('src', 'https://www.youtube.com/embed/' + match[2] + '?autoplay=0&enablejsapi=1').show();
} else {
// Do anything for not being valid
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
foo
<iframe class="videoObject" src=""></iframe>
</li>
<li>
bar
<iframe class="videoObject" src=""></iframe>
</li>
<li>
foo https://www.youtube.com/watch?v=Vr3ya_uPmxg
<iframe class="videoObject" src=""></iframe>
</li>
</ul>