开发者

Strip URL to get YouTube ID

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜