0

I am 'sending' some data in a url:

foo.htm?mydata

From searching around I know that I must use something like:

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

But I am a bit perplexed by this. Could someone help me out in deciphering this at all I simply want the end result to be placing mydata in a var, eg:

var newvar = mydata

Thanks heaps in advance!

MeltingDog
  • 14,310
  • 43
  • 165
  • 295
  • Here a lot of info: http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript – Krycke Aug 02 '12 at 08:01
  • @Krycke if you actually look at the link you posted, you can tell that the function on the question here is taken from there.. – Andreas Wong Aug 02 '12 at 08:02

2 Answers2

2

The getParameterByName function (I assume you got it from here), is written to retrieve a query string value. This means, you can access data from the URL when it looks like this:

yourdomain.com/index.html?key=value&anotherkey=anothervalue

Now you can do this:

var firstKey = getParameterByName("key");
var secondKey = getParameterByName("anotherkey");

As described in your question, you don't have key/value pairs. If this is the case, and you only need the part after the ?, simply use the following by using the split method:

var newvar = document.URL.split("?")[1];

I do suggest you use the key/value method though, in case you want to pass on more variables in the future.

Community
  • 1
  • 1
MarcoK
  • 6,090
  • 2
  • 28
  • 40
  • ah thanks this seems to be what I need! my url is not correct. I get this error though in my console: Uncaught ReferenceError: getParameterByName is not defined. Do I need a plugin for this? – MeltingDog Aug 02 '12 at 09:04
  • It looks like you're calling the function before it's created; try placing the function in the code before the part where you're calling it from. There is no need for any plugin: The get getParameterByName is the function that you defined in your original post. – MarcoK Aug 02 '12 at 09:11
1

Maybe this library is interesting if you are in need of a lot of uri parsing:

https://github.com/medialize/URI.js

Luceos
  • 6,629
  • 1
  • 35
  • 65