0

So I've seen lots of scripts to grab the YouTube ID from a URL with JavaScript, but I can't find or figure out how to grab the ID along with any additional variables. I have a PHP script which can do it, but I'd like to do this with JavaScript. Does anyone know how this can be accomplished?

I doubt it's necessary but here are the two scripts I'm using

JavaScript for video ID...

url = $(this).text();
var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]*).*/;
var match = url.match(regExp);
if (match&&match[2].length==11){
    alert(match[2]);
}else{
   alert("not youtube");
}

And PHP...

if (preg_match('%(?:youtube\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match)) {
$youtubeid = $match[1];
$getyt = (parse_url($url));
}
if(strlen($getyt['fragment']) > 0) {
$addhash = '#' . $getyt['fragment'];
}
$embed = "http://www.youtube.com/embed/$youtubeid?wmode=opaque&autoplay=1$addhash";

The PHP one is pretty good, except that it only works for hash tags. My primary reason for wanting the additional variables is for when someone wants to specify a start time. So if anyone can tell me how I can grab the URL and additional paramaters (or just the specified starting time of the video) then I'd really appreciate it, because I'm absolutely lost.

Ian
  • 1,850
  • 6
  • 23
  • 38
  • http://stackoverflow.com/questions/9552883/regex-to-extract-domain-and-video-id-from-youtube-vimeo-url/9552934#9552934 - he has some code, you may need to modify a bit – Joseph Mar 08 '12 at 09:17
  • That only gets the ID from the videos, which I already know how to do. It's the grabbing additional paramaters I'm having trouble with. Thank you though. – Ian Mar 08 '12 at 09:19
  • Regular expressions are about pattern matching, but you give us nothing to match! How should that additional parameter look like? It would work exactly the same way you use to get video ID. Search for the parameter and put the according value into a capturing group. – stema Mar 08 '12 at 09:41

1 Answers1

1

This creates an associative array named video_parameters:

function extractParameters(url)
{
    var query = url.match(/.*\?(.*)/)[1];
    var assignments = query.split("&")
    var pair, parameters = {};
    for (var ii = 0; ii < assignments.length; ii++)
    { 
        pair = assignments[ii].split("=");
        parameters[pair[0]] = pair[1];
    }
    return parameters;
}

url = "http://www.youtube.com/watch?v=gkU&list=UUa3Q&feature=plcp";
video_parameters = extractParameters(url);

// video_parameters["v"]
// > "gkU"
// video_parameters["list"]
// > "UUa3Q"

See How can I get query string values in JavaScript? for methods that handle special chars.

Community
  • 1
  • 1
0eggxactly
  • 4,642
  • 1
  • 16
  • 16