我正在使用脚本从 URL 获取视频 ID,但当 URL 格式更改时失败
var url = $(this).attr("href");
// Get video ID
var video_id = url.split('v=')[1];
var ampersandPosition = video_id.indexOf('&');
if(ampersandPosition != -1) {
video_id = video_id.substring(0, ampersandPosition);
}
var getvideoid = video_id;
在 https://www.youtube.com/watch?v=KJwYBJMSbPI 下工作正常,但在 https://youtu.be/poh7M2dLn5U?si=QbJekXikzuxYxAaJ
时失败您应该能够通过检查 URL 的主机并更改获取 ID 的方式轻松获取这些信息。
此外,在处理 URL 时使用 URL API。这将使事情变得更加容易。
const pageLink = 'https://www.youtube.com/watch?v=KJwYBJMSbPI';
const sharedLink = 'https://youtu.be/KJwYBJMSbPI?si=SPo8xXjlUHb3QnI4';
const getVideoId = (url) => {
const videoUrl = new URL(url);
if (videoUrl.host === 'youtu.be')
// trim the leading forward slash
return videoUrl.pathname.replace(/^\//, '');
else // "standard" format
return videoUrl.searchParams.get('v')
};
[pageLink, sharedLink].map(url => {
let videoId = getVideoId(url);
console.log(`URL: ${url} => Video ID: ${videoId}`);
return videoId;
});