“JavaScript get query string” refers to getting parameters from the browser URL after the “?” symbol. Using this method, developers are able to collect all user input or state information from the URL. It’s extremely helpful to build dynamic web applications, as passing or transferring non-sensitive user input data through query string parameters is the most popular way for developers.
As said earlier, the query string part of the URL starts with a ”?” character. Each query string parameter is separated by an ”&” character within the URL.
There are two available options to get the query string parameters from the URL: using Web APIs and using pure JavaScript. In this article, we are going to discuss, one by one, with appropriate code examples, how JavaScript get query string works using both methods.
Table of Contents
Get URL Query Parameters using URLSearchParams Interface Web API
The most correct approach for getting the query string parameters in the browser using JavaScript is to use the URLSearchParams Interface Web API. This is not only the appropriate process but also an elegant way to work with URL query strings in JS.
The URLSearchParams() constructor takes a URL containing query strings as a single argument and returns an iterable URLSearchParams object, allowing iteration through all key value pairs within the object and maintaining the same order as they are positioned or placed in the query string.
The URLSearchParams interface has only one instance property. And the property is “size”. This property returns the total number of search parameter entries. Give a quick look at the below example:
<script>
// javascript get query string code example
var queryStrings = new URLSearchParams("a=1&b=2&c=3&d=1");
// get the total number of search parameter or query string parameter from URL
console.log(queryStrings.size); // Output: 4
</script>
The window.location.search property is used to get the query string from the current URL of the web page. So to get a parameter from the current URL or all query string parameters, you can pass it as an argument to the URLSearchParams() constructor.
Code Example: JS Get Query String
<script>
// JavaScript Program to get Query String Values
const currURL = new URL('https://coderstechzone.com?category=JavaScript&pageNo=1&topic=queryParams');
const queryStringParams = new URLSearchParams(currURL.search);
// Iterate to get parameter from url js
for (var item of queryStringParams) {
console.log(item);
}
// The for loop iterate all query parameters
// Check a specific user query parameter from URL
console.log(queryStringParams.has("category"));
// log all url parameters javascript
console.log(queryStringParams.toString());
</script>
Output: JS Get Query String
Code Explanation: JavaScript Get Query String
Here we declare a URL first. Then pass this URL to the URLSearchParams() constructor as a parameter. In return, we received an iterable URLSearchParams object.
A for loop is used to print all URL parameters in the browser console.
The has() method is used to check whether a specific query parameter is present within the URL. Since the “category” query string is available in our mentioned URL, the has() method returns true. In this way, you can check your required query string parameters from an URL.
In the last line, we just print the whole query string part in the JS console.
Code Example to Get Parameter From Browser URL
<script>
// http://runcode.html?itemID=1102&pID=11&discountID=1342
// window.location.search returns current browser URL
// URLSearchParams returns all query parameters only not the base URL
// JavaScript Program to get Query String Values
const queryStringParams = new URLSearchParams(window.location.search);
// Iterate to get parameter from url js
for (var item of queryStringParams) {
console.log(item);
}
// The for loop iterate all query parameters
// If a query parameter exist in URL then print the query string value
if(queryStringParams.has("itemID"))
console.log('itemID: ' + queryStringParams.get("itemID"))
if(queryStringParams.has("pID"))
console.log('pID: ' + queryStringParams.get("pID"))
if(queryStringParams.has("itemID"))
console.log('discountID: ' + queryStringParams.get("discountID"))
// log all url parameters javascript
console.log(queryStringParams.toString());
</script>
Output: Print Parameter From Browser URL
So here in the above code example, we collect the URL from the current browser. Identify and list down all query parameters by passing URLSearchParams, then iterate and print all query parameters into the console log.
In the second part, check a specific parameter from the browser URL. If the specified query parameter exists, then print the query parameter.
To get the query string parameter value, we used the URLSearchParams instance get() method.
Instead of using a for loop, URLSearchParams provides us with four more iteration methods that we can use to loop through the query parameters.
- URLSearchParams.entries()
- URLSearchParams.keys()
- URLSearchParams.values()
- URLSearchParams.forEach()
So far, we have described the has() and get() methods. Along with that, the URLSearchParams has other instance methods, such as append(), delete(), entries(), forEach(), getAll(), keys(), etc. To get a query string in Javascript, we also have to know the getAll() method. There is a notable difference between the get() method and the getAll() method. Look at the differences first:
<script>
// http://runcode.html?itemID=1102&pID=11&discountID=1342&pID=12
// window.location.search returns current browser URL
// URLSearchParams returns all query parameters only not the base URL
const queryStringParams = new URLSearchParams(window.location.search);
// Iterate to get parameter from url js
for (var item of queryStringParams) {
console.log(item);
}
// get() method return only the first value of a specific query string
// getAll() method returns all the value of a specific query string
console.log('pID: ' + queryStringParams.get("pID"))
console.log('pID: ' + queryStringParams.getAll("pID"))
// log all url parameters javascript
console.log(queryStringParams.toString());
</script>
Output: JavaScript Get Query String
If you look at the output, you can easily understand the differences between the URLSearchParams instance get() method and the getAll() method. In the above example, the query parameter pID was mentioned multiple times. And the values are 11 and 12. The get() method returns only the first value. Whereas the getAll() method returns all occurrence values as an array. Here [11,12].
Query Parameter Empty value vs. No value
In some cases, you need to verify query string availability along with their valid values. Such a query parameter may have an empty value or even not have the = sign at all. Like ‘pID=&cID&iTemID=10’;
In these cases, the URLSearchParams are actually unable to determine the differences between a parameter with no value, which means an empty value after the = sign, and a parameter that doesn’t have the = sign at all.
<script>
// http://runcode.html?itemID=1102&pID=&discountID&cID=15
// window.location.search returns current browser URL
// URLSearchParams returns all query parameters only not the base URL
const queryStringParams = new URLSearchParams(window.location.search);
// returns '' in all cases
// here no value for pID query parameter after the = sign
// and even no = sign after discountID query parameter
console.log('pID: ' + queryStringParams.get("pID"))
console.log('discountID: ' + queryStringParams.get("discountID"))
</script>
At this stage, we are going to end the discussion of the URLSearchParams Interface Web API. Covered almost all corner cases. We hope you enjoyed it a lot. If so, please share our article with your friends to help us grow together. Otherwise, please let us know your concerns by leaving a comment.
Get Query String Values Using Pure JavaScript
Using JavaScript’s basic knowledge of string parsing techniques, we can easily build a get query string custom function to do the job. First, create a function getQueryString(url) that receives an URL as an argument with query parameters, parses them, and prints them all at once on the console.
Parse all query string parameters from the URL using the split characters ‘?’, ‘&’, and finally ‘=’ in a sequential order. Keep in mind, too, to avoid outside bounds and undefined errors.
The below code example shows the use of the above-explained approach and show you how JavaScript get query string works.
<script>
// JS function to get url query parameters
function getQueryString(url) {
// Check the array lengths first
// otherwise you will get
// TypeError: Cannot read properties of undefined
// you can use different variables to store split result
// to avoid same operations multiple times
if(url.split('?')[1]){
var queryStrings = url.split('?')[1].split('&');
var params = {};
for (var paramValues of queryStrings) {
console.log(paramValues.split('=')[0]+': '+paramValues.split('=')[1]);
}
}
}
getQueryString('http://runcode.html?itemID=1102&pID=11&discountID=1342&pID=12');
</script>
Output
5 Best Practices to Get Query Params from URL
- The URLSearchParams web API is working properly in all modern browsers but may not work properly for old browsers.
- If you are working on a legacy system, you can consider using a third-party library like query-string or qs.
- To handle duplicate query parameters, use the getAll() method. Because the get() method only returns the specified parameter’s first occurrence.
- If you are planning to go with a plain JS custom function, then handle URL encoding properly.
- Regarding security issues, parsing query parameters can be risky. Validate and sanitize it first before using it.
Conclusion
Query string values always provide us navigational or decision-making information. The information might be a category ID or a choice option that helps us generate an HTML view for the user. More clearly, we can use those query string values or information to generate the business logic of our application. So knowing the retrieval of query string values is very important for us.
How does JavaScript get query string works? Choose your solution elegantly from our above-mentioned two approaches. We hope this article will help you a lot. Happy coding!
FAQs on “JavaScript Get Query String”
Why URLSearchParams returning null for the first query string?
If you manually provide a URL or are not reading the URL from the browser, then create an URL object first and then fetch all query string values with url.search like below:
<script>
const currURL = new URL(‘https://coderstechzone.com?category=JavaScript&pageNo=1&topic=queryParams’);
const queryStringParams = new URLSearchParams(currURL.search);
// use for of loop to get parameter from url js
for (var item of queryStringParams) {
console.log(item);
}
</script>
If you are using window.location.search to get the current URL of the browser, then use the get() or getAll() method like below:
<script>
// http://runcode.html?itemID=1102&pID=11&discountID=1342
// get current URL of browser
const queryStringParams = new URLSearchParams(window.location.search);
console.log(‘pID: ‘ + queryStringParams.get(“pID”))
console.log(‘pID: ‘ + queryStringParams.get(“discountID”))
// log all url parameters javascript
console.log(queryStringParams.toString());
</script>
When to use the URLSearchParams get() method and when to use the getALL() method to retrieve query string values from the URL?
The question only arises if there is a possibility that a single query string parameter can exist multiple times in a single URL.
If you are 100% sure that your required query parameter cannot be duplicated, then use the get() method.
If your required query parameter can be duplicated and you need all values at a time, then use the getAll() method. In this case, the get() method only returns the first value and omits the rest of the other values of your required query parameter.
🏋️♂️ Discover Code Blocks From 20+ yrs JS Expert
💥 Asp.net C# Developer
🏆 Solution Architect
👨✈️ Database Administrator
📢 Speaker
🎓 MCTS since 2009
Leave a Reply