youtube url code example
Example 1: get youtube embed code from url
<----------------------------------- HTML ---------------------------------->
YouTube ID: <span id="myId"></span>
<br />
<br />
Embed code: <pre id="myCode"></pre>
function getId(url) {
var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
var match = url.match(regExp);
if (match && match[2].length == 11) {
return match[2];
} else {
return 'error';
}
}
<----------------------------------- JS ---------------------------------->
var myId = getId('http://www.youtube.com/watch?v=zbYf5_S7oJo');
$('#myId').html(myId);
$('#myCode').html('<iframe width="560" height="315" src="//www.youtube.com/embed/' + myId + '" frameborder="0" allowfullscreen></iframe>');
Example 2: vaidate youtube url
function matchYoutubeUrl(url) {
var p = /^(?:https?:\/\/)?(?:m\.|www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
if(url.match(p)){
return url.match(p)[1];
}
return false;
}