1

Sorry, I am new at this, so bear with me.

In JavaScript, how can I get the contents of the url after the question mark?

So in this url:

http://www.example.com/index.html#anchor?param1=value1&param2=value2

I want an array of values:

{'param1' : 'value1', 'param2' : 'value2'}

Is there a function for doing this in javascript?

1
  • 1
    you have to write your own. there is nothing built in. I was bored so I wrote this the other day gist.github.com/rlemon/c627d5bd6d9a72d1cdd9 (untested, and probably could do for a lot of improvements) Commented Jul 24, 2014 at 20:06

1 Answer 1

2

You can do something like this:

var parameters = window.location.search
    .substring(1)
    .split(/&/)
    .reduce(function(parameters, element) {
        var keyValuePair = element.split(/=/);
        parameters[keyValuePair[0]] = keyValuePair[1];

        return parameters;
    }, {});

Now parameters will contain a map of your parameter values keyed by parameter name.

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

2 Comments

Thank you, this worked perfectly. I will accept your answer in a few minutes - SE says I can't do it for another 8 minutes.
@user3799837 No worries.