0

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>

jsFiddle

babusi
  • 520
  • 1
  • 8
  • 27

1 Answers1

0

I prefer you to create virtual A element, then you get access to some helpful DOM methods to parse it's href value like hostname, protocol, pathname, search, hash, etc. Then it's easier to validate the url parts. I wrote a small function, it returns:

  • false if the URL is not youtube url,
  • empty string if it is youtube url but without video ID
  • string id.

var links = 
  ['https://youtube.com/watch?v=01jcwGApTWA',
   'https://youtube.com/watch?v=01jcwGApTWA&t',
   'https://youtu.be/01jcwGApTWA?t=31',
   'https://www.youtube.com/watch?v=Ujqdle7CvIU&spfreload=10',
   'https://www.youtube.com/watch?v=nQ9ww9E_1C4',
   'https://www.youtube.com/embed/nQ9ww9E_1C4',
   'https://www.youtube.com/embed/nQ9ww9E_1C4?autoplay=1',
   'https://www.youtube.com/embed/nQ9ww9E_1C4?playlist=XGSy3_Czz8k&loop=1',
   'https://www.youtube.com',
   'http://anothersite.com'];

function isYoutube(getURL){
 if(typeof getURL!=='string') return false;
 var newA = document.createElement('A');
 newA.href = getURL;
 var host = newA.hostname;
 var srch = newA.search;
 var path = newA.pathname;
 
 if(host.search(/youtube\.com|youtu\.be/)===-1) return false;
 if(host.search(/youtu\.be/)!==-1) return path.slice(1);
 if(path.search(/embed/)!==-1) return /embed\/([A-z0-9]+)(\&|$)/.exec(path)[1];
 var getId = /v=([A-z0-9]+)(\&|$)/.exec(srch);
 if(host.search(/youtube\.com/)!==-1) return !getId ? '':getId[1];
 
}

console.log(isYoutube(links[0]));
console.log(isYoutube(links[1]));
console.log(isYoutube(links[2]));
console.log(isYoutube(links[3]));
console.log(isYoutube(links[4]));
console.log(isYoutube(links[5]));
console.log(isYoutube(links[6]));
console.log(isYoutube(links[7]));
console.log(isYoutube(links[8]));
console.log(isYoutube(links[9]));
Paweł
  • 4,238
  • 4
  • 21
  • 40