views:

178

answers:

3

I want to get the v=id from youtube's URL with javascript(no jquery, pure javascript);

Example Youtube URL formats:


http://www.youtube.com/watch?v=u8nQa1cJyX8&a=GxdCwVVULXctT2lYDEPllDR0LRTutYfW

http://www.youtube.com/watch?v=u8nQa1cJyX8

or any other youtube format what contains a video id in the url

Result from these formats


u8nQa1cJyX8

+1  A: 

You don't need to use a regular expression for this.

var video_id = window.location.search.split('v=')[1];
var ampersandPosition = video_id.indexOf('&');
if(ampersandPosition != -1) {
  video_id = video_id.substring(0, ampersandPosition);
}
Jacob Relkin
+1  A: 

Don't try it the hard way. Just use String.split(). Regex isn't entirely the right tool for parsing.

function getParameter(url, name) {
    var urlparts = url.split('?');
    if (urlparts.length > 1) {
        var parameters = urlparts[1].split('&');
        for (var i = 0; i < parameters.length; i++) {
            var paramparts = parameters[i].split('=');
            if (paramparts.length > 1 && unescape(paramparts[0]) == name) {
                return unescape(paramparts[1]);
            }
        }
    }
    return null;
}

alert(getParameter('http://www.youtube.com/watch?v=u8nQa1cJyX8', 'v')); // u8nQa1cJyX8 

It makes the function also reuseable for other purposes than only youtube url's.

BalusC
pferdefleisch
@pferdefleisch: such an url is **syntactically invalid**. The parameter names and values should be [url-encoded](http://en.wikipedia.org/wiki/Percent-encoding) as per the specification (the `=` which does not represent name-value separator should then become `%3D` and so on). The `unescape()` function decodes this.
BalusC
A: 

Well, the way to do it with simple parsing would be: get everything starting after the first = sign to the first & sign.

I think they had a similiar answer here:

http://stackoverflow.com/questions/2916544/parsing-a-vimeo-id-using-javascript

karlphillip
CIRK
karlphillip