32

How to extract the query string from the URL in javascript?

Thank you!

Kees C. Bakker
33.6k31 gold badges120 silver badges210 bronze badges
asked May 25, 2010 at 18:41
1

10 Answers 10

48

You can easily build a dictionary style collection...

function getQueryStrings() { 
 var assoc = {};
 var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
 var queryString = location.search.substring(1); 
 var keyValues = queryString.split('&'); 
 for(var i in keyValues) { 
 var key = keyValues[i].split('=');
 if (key.length > 1) {
 assoc[decode(key[0])] = decode(key[1]);
 }
 } 
 return assoc; 
} 

And use it like this...

var qs = getQueryStrings();
var myParam = qs["myParam"]; 
codeling
11.5k6 gold badges48 silver badges76 bronze badges
answered May 25, 2010 at 18:44
Sign up to request clarification or add additional context in comments.

6 Comments

I hope you don't mind, I edited your answer. unescape is deprecated and should be replaced with decodeURIComponent, you shouldn't decode the full search string because it will decode encoded ampersands or equals in the parameters e.g. ?test=fish%26chips. Also, I improved it to correctly decode + into a space. See my answer to a similar question here
@Andy No, I don't mind at all! I agree with you. It would have handled basic query strings just fine, but now this is a more complete answer.
It says: Uncaught SyntaxError: Invalid regular expression: /+/: Nothing to repeat, should I care?
@Tom Yes that is an error that needs to be fixed (It is @Andy E's fault :P) I've updated the answer to be correct.
I was noticing that the function was failing if no parameters were specified, so I edited the function (pending peer review)! With my small addition, it would return an empty array if there are no parameters, which I think is the expected result (instead of an uncaught exception).
|
37

If you're referring to the URL in the address bar, then

window.location.search

will give you just the query string part. Note that this includes the question mark at the beginning.

If you're referring to any random URL stored in (e.g.) a string, you can get at the query string by taking a substring beginning at the index of the first question mark by doing something like:

url.substring(url.indexOf("?"))

That assumes that any question marks in the fragment part of the URL have been properly encoded. If there's a target at the end (i.e., a # followed by the id of a DOM element) it'll include that too.

answered May 25, 2010 at 18:42

Comments

3

Here's the method I use...

function Querystring() {
 var q = window.location.search.substr(1), qs = {};
 if (q.length) {
 var keys = q.split("&"), k, kv, key, val, v;
 for (k = keys.length; k--; ) {
 kv = keys[k].split("=");
 key = kv[0];
 val = decodeURIComponent(kv[1]);
 if (qs[key] === undefined) {
 qs[key] = val;
 } else {
 v = qs[key];
 if (v.constructor != Array) {
 qs[key] = [];
 qs[key].push(v);
 }
 qs[key].push(val);
 }
 }
 }
 return qs;
}

It returns an object of strings and arrays and seems to work quite well. (Strings for single keys, arrays for the same key with multiple values.)

kleopatra
51.7k28 gold badges103 silver badges220 bronze badges
answered Mar 11, 2011 at 3:02

Comments

3

You need to simple use following function.

function GetQueryStringByParameter(name) {
 name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
 var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
 results = regex.exec(location.search);
 return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
 }

--- How to Use ---

var QueryString= GetQueryStringByParameter('QueryString');
answered Jul 24, 2014 at 8:11

Comments

3

There is a new API called URLSearchParams in browsers which allow you to extract and change the values of the query string.

Currently, it seems to be supported in Firefox 44+, Chrome 49+ and Opera 36+.

Initialize/Input

To get started, create a new URLSearchParams object. For current implementations, you need to remove the "?" at the beginning of the query string, using slice(1) on the querystring, as Jake Archibald suggests:

var params = new URLSearchParams(window.location.search.slice(1)); // myParam=12

In later implementations, you should be able to use it without slice:

var params = new URLSearchParams(window.location.search); // myParam=12

Get

You can get params from it via the .get method:

params.get('myParam'); // 12

Set

Params can be changed using .set:

params.set('myParam', 'newValue');

Output

And if the current querystring is needed again, the .toString method provides it:

params.toString(); // myParam=newValue

There are a host of other methods in this API.

Polyfill

As browser support is still pretty thin, there is a small polyfill by Andrea Giammarchi (<3kB).

answered Feb 24, 2016 at 17:38

1 Comment

This is great. I'd like to add one other positive about this method is that it appears to decode the values automatically. For example, if a value contains an encoded @ sign (%40), this method will return "@" instead of the encoded value of "%40".
1

Very Straightforward!

function parseQueryString(){
 var assoc = {};
 var keyValues = location.search.slice(1).split('&');
 var decode = function(s){
 return decodeURIComponent(s.replace(/\+/g, ' '));
 };
 for (var i = 0; i < keyValues.length; ++i) {
 var key = keyValues[i].split('=');
 if (1 < key.length) {
 assoc[decode(key[0])] = decode(key[1]);
 }
 }
 return assoc;
}
answered Jul 23, 2013 at 7:22

Comments

1

Works for me-

function querySt(Key) {
 var url = window.location.href;
 KeysValues = url.split(/[\?&]+/); 
 for (i = 0; i < KeysValues.length; i++) {
 KeyValue= KeysValues[i].split("=");
 if (KeyValue[0] == Key) {
 return KeyValue[1];
 }
 }
}
function GetQString(Key) { 
 if (querySt(Key)) {
 var value = querySt(Key);
 return value; 
 }
 }
nils
27.4k6 gold badges74 silver badges82 bronze badges
answered Jun 17, 2014 at 9:11

Comments

0

You can use this Javascript :

function getParameterByName(name) {
 var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
 return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}

OR

You can also use the plugin jQuery-URL-Parser allows to retrieve all parts of URL, including anchor, host, etc.

Usage is very simple and cool:

$.url().param("itemID")

via James&Alfa

answered Jun 17, 2014 at 9:20

Comments

0

I have use this method

function getString()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
 hash = hashes[i].split('=');
 vars.push(hash[0]);
 vars[hash[0]] = hash[1];
}
return vars;
}
var buisnessArea = getString();
answered Jun 18, 2015 at 11:36

Comments

0
// Assuming "?post=1234&action=edit"
var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?post=1234&action=edit&active=1"
Enea Dume
3,2383 gold badges25 silver badges40 bronze badges
answered Aug 20, 2018 at 11:13

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.