0

I am trying to grab a specific paramater from a url such as www.internets.com?param=123456

I am trying it with something like this..

$j.extend({
  getUrlVars: function(){
   return window.location.href.slice(window.location.href.indexOf('?')).split(/[&?]{1}[\w\d]+=/);
  }
});
var allVars = $j.getUrlVars('param');

The weird thing is the variable is returning a comma so in this example it looks like ,123456

Where is that coming from?!

3 Answers 3

1

split returns an array of substrings, so the comma is coming from the serialization of the array.

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

2 Comments

oh ok.. thanks. Do you know what the proper way to write this would be then?
given what you already have, the simplest approach is to tack [1] onto the end (if you want the first param), e.g. window.location.href.indexOf('?')).split(/[&?]{1}[\w\d]+=/)[1]
0

Have a look here: http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html

This seems to work for me.

1 Comment

Thanks... I did try this but it only returns the name of the parameter for me, so in this example param.. but not the value 123..
0

You're asking the javascript to split the string into an array based on the rules in your regex, so the string "?param=123456" turns into an array where everything up to the = is simply a separator, so it sees two keys: an empty string and 123456.

EDIT - You can still use split, just use a different separator. The indexOf is telling it to look at the substring after the position of the '?', so if you split on '=' it would provide an array where one value is a parameter name (possibly with a '?' or '&', so just remove it) and the next value is the value sent in after the equal sign.

You can also get a little more in depth with your regex and processing like so:

var q = window.location.search; // returns everything after '?'
var regEx = /[^?& =]([\w]*)[^!?& =]/g;
var array = q.match(regEx);
var vars = new Array();
for (var i = 0; i < array.length; i++) {
    if ((i % 2) == 0) {
        vars[array[i]] = array[i + 1];
    }
}

Which will leave you with an array where the keys are the param names, and their values are the associated values from the query string.

1 Comment

See my revised comment. Emmett's solution below is the simplest, so use what works best for you while not overburdening your code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.