我需要从 youtube 视频网址获取 id。我正在使用 split 方法,但在控制台中它给出以下错误
Uncaught TypeError: Cannot read property 'split' of undefined
我的视频网址是:
https://www.youtube.com/embed/juIJGBxj-4w
我的代码是
id = url.split('/')[1].split('embed')[1];
最佳答案
The regular expression will extract the video ID from any YouTube URL and it works with shortened URLs (youtu.be) and embed URLs (youtube.com/embed/) as well.
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.");
}
}
关于javascript - 分割 youtube 视频 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30522323/