Youtube video code
Extracting the Youtube video code from urls using regular expressions
by Alon Rotem
HTML
<div id="results"></div>
CSS
#results{
font-family:arial;
font-size: 11pt;
line-height:27px;
}
.code {
background-color: yellow;
}
.err {
background-color: pink;
}
JavaScript
function extractYoutubeVideoCode(urlOrVideoCode){
var code = "";
var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
var match = urlOrVideoCode.match(regExp);
if (match && match[7].length == 11) {
code = match[7];
}
if(!code) {
regExp = /youtube.com\/\??v[i]??[\/=]([^\?&#]*)/;
var match = urlOrVideoCode.match(regExp);
if(match && match[1].length == 11)
code = match[1];
}
if((!code) && (urlOrVideoCode.indexOf("youtube") < 0) && (urlOrVideoCode.indexOf("youtu.be") < 0) && (urlOrVideoCode.length==11)) {
code = urlOrVideoCode;
}
return code;
}
function writeLog(text) {
$("#results").html($("#results").html() + text + "<br/>");
}
function testYoutubeExtractor(urlOrVideoCode){
writeLog(urlOrVideoCode + " ► <span class='"+((typeof(extractYoutubeVideoCode(urlOrVideoCode)) == typeof("undefined"))? "code" : "err") +"'>" + extractYoutubeVideoCode(urlOrVideoCode) +...