How do i query a parameter in javascript?
Update: Jan-2022 Show
Using
Update: June-2021 For a specific case when you need all query params:
Update: Sep-2018 You can use URLSearchParams which is simple and has decent (but not complete) browser support.
Original You don't need jQuery for that purpose. You can use just some pure JavaScript:
Usage:
NOTE: If a parameter is
present several times ( NOTE: The function is case-sensitive. If you prefer case-insensitive parameter name, add 'i' modifier to RegExp NOTE: If you're getting a no-useless-escape eslint error, you can replace This is an update based on the new URLSearchParams specs to achieve the same result more succinctly. See answer titled "URLSearchParams" below. 16 Some of the solutions posted here are inefficient. Repeating the regular expression search every time the script needs to access a parameter is completely unnecessary, one single function to split up the parameters into an associative-array style object is enough. If you're not working with the HTML 5 History API, this is only necessary once per page load. The other suggestions here also fail to decode the URL correctly.
Example querystring:
Result:
This could easily be improved upon to handle array-style query strings too. An example of this is here, but since array-style parameters aren't defined in RFC 3986 I won't pollute this answer with the source code. For those interested in a "polluted" version, look at campbeln's answer below. Also, as pointed out in the comments, If you're using a server-side preprocessing language, you might want to use its native JSON functions to do the heavy lifting for you. For example, in PHP you can write:
Much simpler! #UPDATED
So, this is the approach to manage it:
2 ES2015 (ES6)
Without jQuery
With an URL like
Google methodTearing Google's code I found the method they use:
It is obfuscated, but it is understandable. It does not work because some variables are undefined. They start to look for parameters on the url from In the end the object My method as a jQuery plugin
Usage
Performance test (split method against regex method) (jsPerf)Preparation code: methods declaration Split test code
Regex test code
Testing in Firefox 4.0 x86 on Windows Server 2008 R2 / 7 x64
0 URLSearchParamsFirefox 44+, Opera 36+, Edge 17+, Safari 10.3+ and Chrome 49+ support the URLSearchParams API:
There is a google-suggested URLSearchParams polyfill for the stable versions of IE. It is not standardized by W3C, but it is a living standard by WhatWG. You can use it on
or
Or of course on any URL:
You can get params also using a shorthand
You read/set parameters through the A reference implementation and a sample page are available for auditing and testing. 2 Just another recommendation. The plugin Purl allows to retrieve all parts of URL, including anchor, host, etc. It can be used with or without jQuery. Usage is very simple and cool:
However, as of Nov 11, 2014, Purl is no longer maintained and the author recommends using URI.js instead. The jQuery plugin is different in that it focuses on elements - for usage with strings, just use
0 tl;drA quick, complete solution, which handles multivalued keys and encoded characters.
Multi-lined:
What is all this code... Read more... about the Vanilla JavaScript solution.To access different parts of a URL use Easiest (dummy) solution
Multi-valued keysSimple key check
Encoded characters?Use
####Example: # From comments **\*!!!** Please note, that `decodeURIComponent(undefined)` returns string `"undefined"`. The solution lies in a simple usage of [`&&`][5], which ensures that `decodeURIComponent()` is not called on undefined values. _(See the "complete solution" at the top.)_
If the querystring is empty (`location.search == ""`), the result is somewhat misleading `qd == {"": undefined}`. It is suggested to check the querystring before launching the parsing function likeso:
0 Roshambo on snipplr.com has a simple script to achieve this described in Get URL Parameters with jQuery | Improved. With his script you also easily get to pull out just the parameters you want. Here's the gist:
Then just get your parameters from the query string. So if the URL/query string was Just call UZBEKJON has a great blog post on this as well, Get URL parameters & values with jQuery. 0 If you're using jQuery, you can use a library, such as jQuery BBQ: Back Button & Query Library.
Edit: Adding Deparam Example:
If you want to just use plain JavaScript, you could use...
Because of the new HTML History API and specifically This version will update its internal cache of parameters each time the history changes. 0 Just use two splits:
I was reading all the previous and more complete answers. But I think that is the simplest and faster method. You can check in this jsPerf benchmark To solve the problem in Rup's comment, add a conditional split by changing the first line to the two below. But absolute accuracy means it's now slower than regexp (see jsPerf).
So if you know you won't run into Rup's counter-case, this wins. Otherwise, regexp.
0 Here's my stab at making Andy E's excellent solution into a full fledged jQuery plugin:
The syntax is:
Best of both worlds! 0 If you're doing more URL manipulation than simply parsing the querystring, you may find URI.js helpful. It is a library for manipulating URLs - and comes with all the bells and whistles. (Sorry for self-advertising here) to convert your querystring into a map:
(URI.js also "fixes" bad querystrings like 0 I like Ryan Phelan's solution. But I don't see any point of extending jQuery for that? There is no usage of jQuery functionality. On the other hand, I like the built-in function in Google Chrome: window.location.getParameter. So why not to use this? Okay, other browsers don't have. So let's create this function if it does not exist:
This function is more or less from Ryan Phelan, but it is wrapped differently: clear name and no dependencies of other javascript libraries. More about this function on my blog. 0 Here is a fast way to get an object similar to the PHP $_GET array:
Usage:
For the query string
0 Keep it simple in plain JavaScript code:
Call it from anywhere in the JavaScript code:
0 From the MDN:
0 These are all great answers, but I needed something a bit more robust, and thought you all might like to have what I created. It is a simple library method that does dissection and manipulation of URL parameters. The static method has the following sub methods that can be called on the subject URL:
Example:
Code golf:
Display it!
On
my Mac:
0 I use regular expressions a lot, but not for that. It seems easier and more efficient to me to read the query string once in my application, and build an object from all the key/value pairs like:
For a URL like
0 Roshambo jQuery method wasn't taking care of decode URL
Just added that capability also while adding in the return statement
Now you can find the updated gist:
I like this one (taken from jquery-howto.blogspot.co.uk):
Works great for me. 0 Here's my edit to this excellent answer - with added ability to parse query strings with keys without values.
IMPORTANT! The parameter for that function in the last line is different. It's just an example of how one can pass an arbitrary URL to it. You can use last line from Bruno's answer to parse the current URL. So what exactly changed? With url I needed an object from the query string, and I hate lots of code. It may not be the most robust in the universe, but it's just a few lines of code.
A URL like
3 Here's an extended version of Andy E's linked "Handle array-style query strings"-version. Fixed a bug ( It will handle the following querystring...
...making it into an object that looks like...
As you can see above, this version handles some measure of "malformed" arrays, i.e. -
It seems the jury is somewhat out on repeated keys as there is no spec. In this case, multiple keys are stored as an (fake)array. But do note that I do not process values based on commas into arrays. The code:
3 This is a function I created a while back and I'm quite happy with. It is not case sensitive - which is handy. Also, if the requested QS doesn't exist, it just returns an empty string. I use a compressed version of this. I'm posting uncompressed for the novice types to better explain what's going on. I'm sure this could be optimized or done differently to work faster, but it's always worked great for what I need. Enjoy.
1 If you are using Browserify, you can use the
Further reading: URL Node.js v0.12.2 Manual & Documentation EDIT: You can use URL interface, its quite widely adopted in almost all the new browser and if the code is going to run on an old browser you can use a polyfill like this one. Here's a code example on how to use URL interface to get query parameters (aka search parameters)
You can also use URLSearchParams for it, here's an example from MDN to do it with URLSearchParams:
4
And this is how you can use this function assuming the URL is
1 We've just released arg.js, a project aimed at solving this problem once and for all. It's traditionally been so difficult but now you can do:
or getting the whole lot:
and if you care about the difference between 1 The problem with the top answer on that question is that it's not-supported parameters placed after #, but sometimes it's needed to get this value also. I modified the answer to let it parse a full query string with a hash sign also:
3 How do you create a parameter query?Create a parameter query. Create a select query, and then open the query in Design view.. In the Criteria row of the field you want to apply a parameter to, enter the text that you want to display in the parameter box, enclosed in square brackets. ... . Repeat step 2 for each field you want to add parameters to.. How do you query parameters in a URL?Any word after the question mark (?) in a URL is considered to be a parameter which can hold values. The value for the corresponding parameter is given after the symbol "equals" (=). Multiple parameters can be passed through the URL by separating them with multiple "&".
How will you get the query parameter search?In the View column, click View Settings. Under Site Search Settings, set Site Search Tracking to ON. In the Query Parameter field, enter the word or words that designate internal query parameters, such as term,search,query,keywords. Sometimes query parameters are designated by just a letter, such as s or q.
Can Javascript read URL parameters?The short answer is yes Javascript can parse URL parameter values. You can do this by leveraging URL Parameters to: Pass values from one page to another using the Javascript Get Method. Pass custom values to Google Analytics using the Google Tag Manager URL Variable which works the same as using a Javascript function.
|