Dylan Cross
Dylan Cross

Reputation: 5986

Javascript regex match for certain websites only

I'm not really good with regular expressions, so I'm hoping someone could help come up with something that would fit what I'm trying to do, which is:

I want it to match in the following cases (only for youtube links):

http://www.youtube.com/watch?v=oHg5SJYRHA0
www.youtube.com/watch?v=oHg5SJYRHA0
youtube.com/watch?v=oHg5SJYRHA0
http://youtu.be/oHg5SJYRHA0
www.youtu.be/oHg5SJYRHA0
youtu.be/oHg5SJYRHA0

also in the first three examples, it should match any domain ending, so not just .com

While I'm asking this, I will also need to be able to get the video ID alone as well.

Upvotes: 0

Views: 132

Answers (2)

Marshall
Marshall

Reputation: 4766

You could do the following:

function getYoutubeId(str) {
    var check;
    check = /youtu.be\/(\w+)/.exec(str); 
    if(check) return check[1];
    check = /youtube\.com\/.*v=(\w+)/.exec(str); 
    if(check) return check[1];
    return null;
}

getYoutubeId("http://www.youtube.com/watch?v=oHg5SJYRHA0"); // oHg5SJYRHA0
getYoutubeId("www.youtube.com/watch?v=oHg5SJYRHA0"); // oHg5SJYRHA0
getYoutubeId("youtube.com/watch?v=oHg5SJYRHA0"); // oHg5SJYRHA0
getYoutubeId("http://youtu.be/oHg5SJYRHA0"); // oHg5SJYRHA0
getYoutubeId("www.youtu.be/oHg5SJYRHA0"); // oHg5SJYRHA0
getYoutubeId("youtu.be/oHg5SJYRHA0"); // oHg5SJYRHA0

getYoutubeId(""); // null
getYoutubeId("google.com"); // null
getYoutubeId("youtu.be/"); // null
getYoutubeId("youtube.com/?other=something"); // null

Upvotes: 2

mowwwalker
mowwwalker

Reputation: 17364

This should do the trick:

(?:http://)?(?:www\.)?youtu(?:\.be|be.com)/(?:watch\?v=)?([\d\w]+)

The first captured group is the video id. You can test it here: http://www.regexr.com.

Upvotes: 1

Related Questions