Get the Youtube ID from a Youtube URL (Shortened URL support too)


/ Published in: jQuery
Save to your folder(s)

Use this snippet to check if user supplied URL is a valid Youtube URL. Has support for youtu.be shortened URL's too.


Copy this code and paste it in your HTML
  1. <script type="text/javascript">
  2. // $('#YTembed') is the ID of your input field
  3. $('#YTembed').change(function(){
  4. var txt = $(this).val(); // get the value that the user supplied
  5. var flag = false; // Use this flag variable to discern between good and bad entry > Assumes good
  6. // First try the normal youtube URL:
  7. var arr = txt.split('v=');
  8. if (arr.length > 1){
  9. // normal Youtube URL detected
  10. var vidcode = arr[1].substr(0,11); // Substring get the 11 characters
  11. } else if (txt.indexOf('youtu.be') > -1) {
  12. // Normal URL check failed > try the shortened one
  13. arr = txt.split('youtu.be'); // Split on shortened URL
  14. var vidcode = arr[1].substr(1,11); // Grab the 11 characters from the slash onward
  15. } else {
  16. // No result > Flag for output
  17. flag = true;
  18. }
  19.  
  20. if (!flag) $('#vidfeedback').html('<iframe width="580" height="326" src="http://www.youtube.com/embed/'+vidcode+'" frameborder="0" allowfullscreen></iframe>');
  21. else $('#vidfeedback').html("That doesn't appear to be a Youtube URL. Please try again.<br/>We accept the following formats:<br/>http://www.youtube.com/watch?v=XXXXXXXXXXX or <br/>http://youtu.be/XXXXXXXXXXX");
  22. });
  23. </script>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.