Now we can get more data after the first %20, I mean, all data with spaces, like uri.html?data=more%20than%20one%20space I found this info at stackoverflow.com about speeds on “split” and “regex”:
Also, as Relfor said, using decodeUriComponent we haven’t to look for spaces (%20) or another symbols (like accents). Less lines of code, better results:
If your value has a “&” in it then you’ve got a malformed value. You have to url encode them. In a url query “&” means to start the next var.
What if i want to return default value? For example: http://www.example.com/index.php?id=1&image=awesome.jpg Calling getQueryVariable(“id”) – would return “1”. Calling getQueryVariable(“image”) – would return “awesome.jpg”. What if: http://www.example.com/index.php I still want to return “id” value = “predefined value”
Hi there, Could anyone show me exactly how to apply this in html? I have almost no experience with JS. I have tried dozens of iterations and checked many sites and I’m at my wits end. My query string at the end of the url is ?foo=jim. I have the JS function inside inside the document head. I need ‘jim’ to be inserted as a value of a hidden input field. Below is one of the many iterations I have tried to get this to work.
Hi Amber, I have the same problem as you mentioned in this post and I am wondering if you came up with a solution yet?
@joe – Just change your line : var query = url;
to : var query = url.split(‘?’)[1]; This will split out the query part of the url.
Awesome. I had already a youtube url and just needed the video id. I found this very nice solution: Create a link, set href and now you can use ‘location.search’ too. So I just added this to the function above.
var link = document.createElement("a"); link.href = YOURURL; var query = link.search.substring(1);
This technique only returns “false” when setup exactly like described. link setup: /test.html?id=1&image=awesome.jpg
window.location is not set for arguments in tags. Let’s assume you only need to pass arguments without names, just like function calls. In HTML:
URL parameters (also called query string parameters or URL variables) are used to send small amounts of data from page to page, or from client to server via a URL. They can contain all kinds of useful information, such as search queries, link referrals, product information, user preferences, and more.
In this article, we’ll show you how to parse and manipulate URL parameters using JavaScript.
Getting a URL Parameter
In modern browsers, this has become a lot easier, thanks to the URLSearchParams interface. This defines a host of utility methods to work with the query string of a URL.
Assuming that our URL is https://example.com/?product=shirt&color=blue&newuser&size=m , we can grab the query string using window.location.search :
You can use URLSearchParams.getAll() to return all of the values associated with a particular parameter:
console.log(urlParams.getAll('size'));// [ 'm' ]//Programmatically add a second size parameter. urlParams.append('size','xl');console.log(urlParams.getAll('size'));// [ 'm', 'xl' ]
Iterating over Parameters
URLSearchParams also provides some familiar Object iterator methods, allowing you iterate over its keys, values and entries:
const keys = urlParams.keys(), values = urlParams.values(), entries = urlParams.entries();for(const key of keys)console.log(key);// product, color, newuser, sizefor(const value of values)console.log(value);// shirt, blue, , mfor(const entry of entries)console.log(`$entry[0]>:$entry[1]>`);>// product: shirt// color: blue// newuser:// size: m
Browser Support
Browser support for URLSearchParams is good. At the time of writing, it’s supported in all major browsers.
There’s a polyfill available if you have to support legacy browsers such as Internet Explorer. Or, you could follow along with the rest of this tutorial and learn how to roll your own.
Rolling Your Own Query String Parsing Function
Let’s stay with the URL we were using in the previous section:
Here’s a function to give you all the URL parameters as a neat object:
functiongetAllUrlParams(url)// get query string from url (optional) or windowvar queryString = url ? url.split('?')[1]:window.location.search.slice(1);// we'll store the parameters herevar obj =>;// if query string existsif(queryString)// stuff after # is not part of query string, so get rid of it queryString = queryString.split('#')[0];// split our query string into its component partsvar arr = queryString.split('&');for(var i =0; i arr.length; i++)// separate the keys and the valuesvar a = arr[i].split('=');// set parameter name and value (use 'true' if empty)var paramName = a[0];var paramValue =typeof(a[1])==='undefined'?true: a[1];// (optional) keep case consistent paramName = paramName.toLowerCase();if(typeof paramValue ==='string') paramValue = paramValue.toLowerCase();// if the paramName ends with square brackets, e.g. colors[] or colors[2]if(paramName.match(/\[(\d+)?\]$/))// create key if it doesn't existvar key = paramName.replace(/\[(\d+)?\]/,'');if(!obj[key]) obj[key]=[];// if it's an indexed array e.g. colors[2]if(paramName.match(/\[\d+\]$/))// get the index value and add the entry at the appropriate positionvar index =/\[(\d+)\]/.exec(paramName)[1]; obj[key][index]= paramValue;>else// otherwise add the value to the end of the array obj[key].push(paramValue);>>else// we're dealing with a stringif(!obj[paramName])// if it doesn't exist, create property obj[paramName]= paramValue;>elseif(obj[paramName]&&typeof obj[paramName]==='string')// if property does exist and it's a string, convert it to an array obj[paramName]=[obj[paramName]]; obj[paramName].push(paramValue);>else// otherwise add the property obj[paramName].push(paramValue);>>>>return obj;>
You’ll see how this works soon, but first, here are some usage examples:
See the Pen rQGWpP by SitePoint (@SitePoint) on CodePen.
Things to Know Before Using This Function
Our function assumes the parameters are separated by the & character, as indicated in the W3C specifications. However, the URL parameter format in general is not clearly defined, so you occasionally might see ; or & as separators.
Our function still works if a parameter doesn’t have an equals sign or if it has an equals sign but no value.
The values of duplicate parameters get put into an array.
If you just wanted a function you could drop into your code, you’re done now. If you’d like to understand how the function works, read on.
The following section assumes you know some JavaScript, including functions, objects, and arrays. If you need a refresher, check out the MDN JavaScript reference.
How the Function Works
Overall, the function takes a URL’s query string (the part after the ? and before the # ) and spits out the data in a neat object.
First, this line says, if we’ve specified a URL, get everything after the question mark, but otherwise, just use the URL of the window:
var queryString = url ? url.split('?')[1]:window.location.search.slice(1);
Next, we’ll create an object to store our parameters:
If the query string exists, we’ll start parsing it. First we have to make sure to shave off the part starting from the # , since it’s not part of the query string:
queryString = queryString.split('#')[0];
Now we can split the query string into its component parts:
var arr = queryString.split('&');
That will give us an array that looks like this:
['product=shirt','color=blue','newuser','size=m']
Next, we’ll loop through this array and split each item into a key and a value, which we’ll soon put into our object:
Let’s assign the key and a value to individual variables. If there isn’t a parameter value, we’ll set it to true to indicate that the parameter name exists. Feel free to change this depending on your use case:
var paramName = a[0];var paramValue =typeof(a[1])==='undefined'?true: a[1];
Optionally, you can set all parameter names and values to lowercase. That way, you can avoid situations where someone sends traffic to a URL with example=TRUE instead of example=true and your script breaks. (I’ve seen this happen.) However, if your query string needs to be case sensitive, feel free to omit this part:
Next, we need to deal with the various types of input we can receive in paramName . This could be an indexed array, a non-indexed array, or a regular string.
If it’s an indexed array, we want the corresponding paramValue to be an array, with the value inserted at the correct position. If it’s a non-indexed array, we want the corresponding paramValue to be an array with the element pushed on to it. If it’s a string, we want to create a regular property on the object and assign the paramValue to it, unless the property already exists, in which case we want to convert the existing paramValue to an array and push the incoming paramValue on to that.
To illustrate this, here’s some sample input, with the output we would expect:
Finally, we return our object with the parameters and values.
If your URL has any encoded special characters like spaces (encoded as %20 ), you can also decode them to get the original value like this:
// assume a url parameter of test=a%20spacevar original =getAllUrlParams().test;// 'a%20space'var decoded =decodeURIComponent(original);// 'a space'
Just be careful not to decode something that’s already decoded or else your script will error out, especially if percents are involved.
Anyways, congrats! Now you know how to get a URL parameter, and hopefully have picked up some other tricks along the way.
Conclusion
The code in this article works for the most common use cases where you would get a URL query parameter. If you’re working with any edge cases, such as uncommon separators or special formatting, then be sure to test and adjust accordingly.
If you want to do more with URLs, there are specific libraries available, such as query-string and Medialize URI.js. But since it’s basically string manipulation, it often makes sense just to use plain JavaScript. Whether you use your own code or go with a library, be sure to check everything and make sure it works for your use cases.
Share This Article
Yaphi Berhanu is a web developer who loves helping people boost their coding skills. He writes tips and tricks at http://simplestepscode.com. In his completely unbiased opinion, he suggests checking it out.
Network admin, freelance web developer and editor at SitePoint.