从 youtube 嵌入网址获取 YouTube ID



我只想从以下网址获取youtube id

https://www.youtube.com/embed/cqyziA30whE?controls=1&showinfo=0&rel=0&autoplay=0&loop=0

$(".youtube").click(function () {
console.log(this.href.replace(new RegExp("embed\/", "i"), 'embed/'));
});

这让我获得了整个网址,而我只想在用户单击任何链接时获得 YouTubeIDcqyziA30whE

捕获组中/embed/后面的非问号字符,然后使用该捕获的组:

const str = 'https://www.youtube.com/embed/cqyziA30whE?controls=1&showinfo=0&rel=0&autoplay=0&loop=0';
console.log(
str.match(//embed/([^?]+)/)[1]
);

您也可以懒惰地重复任何字符,直到到达问号:

const str = 'https://www.youtube.com/embed/cqyziA30whE?controls=1&showinfo=0&rel=0&autoplay=0&loop=0';
console.log(
str.match(//embed/(.+)?/)[1]
);

您可以使用正则表达式组并捕获它。

var url = 'https://www.youtube.com/embed/nrGk0AuFd_9?controls=1&showinfo=0&rel=0&autoplay=0&loop=0';
console.log(url.replace(new RegExp("^.*/embed/([a-zA-Z0-9_-]+)?.*", "i"), '$1'));

Split()

带有分隔符字符串,然后使用分隔符?split(( 结果,所需的结果是拆分数组的第一个元素。

var string = "https://www.youtube.com/embed/cqyziA30whE?controls=1&showinfo=0&rel=0&autoplay=0&loop=0";
var words=string.split('/');
console.log(words[4].split('?')[0]);

如果你想要一个聪明的方法来避免RegExp你可以使用这样的HTMLHyperlinkElementUtils.pathname

const href = 'https://www.youtube.com/embed/cqyziA30whE?controls=1&showinfo=0&rel=0&autoplay=0&loop=0'
const a = document.createElement('a')
a.href = href
const id = a.pathname.split('/').pop()
console.log(id)

根据您的代码段,您可以执行以下简单操作:

$(".youtube").click(function() {
console.log(this.pathname.split('/').pop());
});

最新更新