开发者

Strip URL to get YouTube ID

开发者 https://www.devze.com 2023-03-25 13:45 出处:网络
I have: var post = $(\'.post\'); post.find(\'.video embed\').each(function(){ v = $(this); youtubeID = v.attr(\'src\').replace(/^.*youtube.com.*(?:\\/|v=)(\\w+)\\//g,\"\");

I have:

var post = $('.post');
post.find('.video embed').each(function(){
    v = $(this);
    youtubeID = v.attr('src').replace(/^.*youtube.com.*(?:\/|v=)(\w+)\//g,"");
    console.l开发者_JAVA技巧og(youtubeID);
})

Here's an example URL taken from the embed src

http://www.youtube.com/v/_eeZnLX_XBM&rel=0&egm=0&showinfo=0&fs=1

It strips the everything up to /v/ but not the ampersand and everything after that.

I want _eeZnLX_XBM only.


Try with:

youtubeID = v.attr('src').match(/youtube\.com.*?v[\/=](\w+)/)[1];


so just add another replace for the rest:

var post = $('.post');
post.find('.video embed').each(function(){
    v = $(this);
    youtubeID = v.attr('src').replace(/^.*youtube.com.*(?:\/|v=)(\w+)\//g,"").replace(/&.*/g, "");
    console.log(youtubeID);
})


var url = v.attr('src');
youtubeID = url.substring(url.lastIndexOf('/') + 1 ,url.indexOf('&'));


Try this:

$('.post').find('.video embed').each(function(){
    youtubeID = $(this).attr('src').match(/\/([^&/]+)&/)[1];

    console.log(youtubeID);
})

visualization of the regex

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号