0

Possible Duplicate:
Javascript REGEX: How to get youtube video id from URL?

In javascript I need to grab a url variable that can be the first variable but doesn't have to. The url is a string of a url from Youtube. At first I was using regex to replace everything from & on, but then I found out that the video variable isn't always first. I am not good with regex and just have gone with tutorials I can find and double check to make sure it works right. So I need to be able to grab the v=videoletters part. If I can grab that, I think I can figure from then on to make the normal youtube url which is what I need.

Community
  • 1
  • 1
townie
  • 767
  • 2
  • 8
  • 12

1 Answers1

0

Here's a function that does exactly what you asked for:

function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

Found via a Google search on this page: http://www.netlobo.com/url_query_string_javascript.html

So, you would just do:

var videoletters = gup("v");

There are many, many other ways to do this also that you can see via your own search. Here are a few of the others:

How to retrieve query string parameter and values using javascript (Jquery)?

http://www.idealog.us/2006/06/javascript_to_p.html

http://stevenbenner.com/2010/03/javascript-regex-trick-parse-a-query-string-into-an-object/

http://geekswithblogs.net/PhubarBaz/archive/2011/11/21/getting-query-parameters-in-javascript.aspx

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979