拆分youtube视频url

Splitting youtube video url

本文关键字:url 视频 youtube 拆分      更新时间:2023-09-26

我需要从youtube视频url获取id。我正在使用分割方法,但在控制台中它给出了以下错误

Uncaught TypeError: Cannot read property 'split' of undefined

我的视频网址是:https://www.youtube.com/embed/juIJGBxj-4w

我的代码是
id = url.split('/')[1].split('embed')[1];

正则表达式将从任何YouTube URL中提取视频ID它适用于缩短url (youtube .be)和嵌入url(youtube.com/embed/)

 function extractVideoID(url){
        var regExp = /^.*((youtu.be'/)|(v'/)|('/u'/'w'/)|(embed'/)|(watch'?))'??v?=?([^#'&'?]*).*/;
        var match = url.match(regExp);
        if ( match && match[7].length == 11 ){
            return match[7];
        }else{
            alert("Could not extract video ID.");
        }
    }

例如youtube url为'https://www.youtube.com/watch?v=abcdefghij'

,我将用下面的代码分割它

id = url.split('?')[1].split('=')[1];

这个问题比看起来更复杂,因为所有的Youtube URL都不是以www.youtube.com/watch?v=.....开头的,有些有www.youtu.be/...youtube.com/embed/...的模式。

这是我使用的解析器,它每次对任何Youtube URL都有效:

videoId = url.match(/(?:https?:'/'/)?(?:www'.)?(?:youtube'.com'/(?:[^'/]+'/.+'/|(?:v|e(?:mbed)?)'/|.*[?&]v=)|youtu'.be'/)([^"&?'/ ]{11})/i)[0]

假设id总是在最后出现。

function getId(url){
    var splitedValue = url.split("/");
    return splitedValue[splitedValue.length-1];
}
getId("https://www.youtube.com/embed/juIJGBxj-4w");

Output: juIJGBxj-4w

url = "https://www.youtube.com/embed/juIJGBxj-4w"
id = url.split('/');
var indexOfEmbed = id.indexOf("juIJGBxj-4w");
id[indexOfEmbed]

输出:


"juIJGBxj-4w"

此解决方案适用于所有使用regex的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]; // use console.log if your run code in browser console 
} else {
  //error
}

此解决方案适用于所有不含regex的url:

对于这种类型的url<我>

http://www.youtube.com/watch?v=u8nQa1cJyX8&a=GxdCwVVULXctT2lYDEPllDR0LRTutYfW
http://www.youtube.com/watch?v=u8nQa1cJyX8


<我>

 var url ="http://www.youtube.com/watch?v=u8nQa1cJyX8&a=GxdCwVVULXctT2lYDEPllDR0LRTutYfW"
 var video_id = window.location.search.split('v=')[1];// use url insted of window.location.search
Or 
 var video_id = url.split('v=')[1];
    var ampersandPosition = video_id.indexOf('&');
    if(ampersandPosition != -1) {
      video_id = video_id.substring(0, ampersandPosition);
    }