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!

2
  • Here a lot of info: stackoverflow.com/questions/901115/… Commented Aug 2, 2012 at 8: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.. Commented Aug 2, 2012 at 8:02

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
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.
1

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.