views:

450

answers:

2

Just need a little push as I have this almost working.

I want to feed jquery a URL and have it strip everthing but the video url.

Here is my code:

 var url = 'http://www.youtube.com/watch?v=bxp8NWvIeSo';   

$results = url.match("[\\?&]v=([^&#]*)");

alert($results);

  });

I'm getting this as an output -

?v=bxp8NWvIeSo,bxp8NWvIeSo

When I only want

bxp8NWvIeSo

+1  A: 

First, remove the $ in front of results... I assume that was a typo. Next, replace

$results = url.match("[\\?&]v=([^&#]*)");

with

results = url.match("[\?&]v=([^&#]*)")[1];

match() will return an array if there is a successful match. You're currently getting the entire array. What you want is the second element of the array (match()[1]) which is what is inside your capturing parentheses.

ithcy
Correct answer except that the dollar sign is perfectly acceptable in a JavaScript variable identifier and you don't actually need *any* backslashes in the regex at all.
brianpeiris
Sure, $ is valid, but I wouldn't call it good practice, especially when you're using jQuery, which defines $(). You're also right about the backslash but I would leave it in because it reminds me "this is a literal, not a lookahead" :)
ithcy
A: 

if you are not forced to use match, you can use "split":

var getList = function(url, gkey){

        var returned = null;

        if (url.indexOf("?") != -1){

          var list = url.split("?")[1].split("&"),
                  gets = [];

          for (var ind in list){
            var kv = list[ind].split("=");
            if (kv.length>0)
                gets[kv[0]] = kv[1];
        }

        returned = gets;

        if (typeof gkey != "undefined")
            if (typeof gets[gkey] != "undefined")
                returned = gets[gkey];

        }

        return returned;

};

var url = 'http://www.youtube.com/watch?v=bxp8NWvIeSo';
$result = getList(url, "v");
alert($result);
andres descalzo
This worked great. even rolled into an easy to use function :)
Wes