title: How to validate a YouTube URL using JS
body: <p>I'd like to loop through list items <code>onload</code> 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:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>$('li').each(function() {
    var url = $(this).text();
    if (url != undefined || url != '') {
      var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&amp;v=|\?v=)([^#\&amp;\?]*).*/;
      var match = url.match(regExp);
      if (match &amp;&amp; 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&amp;enablejsapi=1').show();
      } else {
        // Do anything for not being valid
      }
    }
  });</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;
  &lt;ul&gt;
    &lt;li&gt;
      foo
      &lt;iframe class="videoObject" src=""&gt;&lt;/iframe&gt;
    &lt;/li&gt;
    &lt;li&gt;
      bar
      &lt;iframe class="videoObject" src=""&gt;&lt;/iframe&gt;
    &lt;/li&gt;
    &lt;li&gt;
      foo https://www.youtube.com/watch?v=Vr3ya_uPmxg
      &lt;iframe class="videoObject" src=""&gt;&lt;/iframe&gt;
    &lt;/li&gt;
  &lt;/ul&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p><a href="https://jsfiddle.net/d2wref9b/" rel="nofollow noreferrer">jsFiddle</a></p>