This question already has an answer here:
If I had a URL such as
http://localhost/search.php?year=2008
How would I write a JavaScript function to grab the variable year and see if it contains anything?
I know it can be done with location.search
but I can’t figure out how it grabs parameters.
My favorite way for getting URL params is this approach:
This is what I like to do:
Of course you can make it more compact using modern syntax or writing everything into one line...
I leave that up to you.
It took me a while to find the answer to this question. Most people seem to be suggesting regex solutions. I strongly prefer to use code that is tried and tested as opposed to regex that I or someone else thought up on the fly.
I use the parseUri library available here: http://stevenlevithan.com/demo/parseuri/js/
It allows you to do exactly what you are asking for:
Grab the params from location.search with one line:
Then, simply:
I used a variant of Alex's - but needed to to convert the param appearing multiple times to an array. There seem to be many options. I didn't want rely on another library for something this simple. I suppose one of the other options posted here may be better - I adapted Alex's because of the straight forwardness.
ES6 answer:
for example: