How to Get URL Parameters in JavaScript
Gone are the days of manually parsing and looping over long query strings in the front end. JavaScript now makes this easier than ever in modern browsers with the URLSearchParams interface, providing a wide variety of built-in functions to parse and manipulate query string data.
What Are URL Parameters?
URL parameters are small bits of data passed in the query string of a URL to another page. They're beneficial when you need to pull customer information, order information, search queries, and much more.
This tutorial will show you how to identify and parse those URL parameters with JavaScript.
Get URL Parameters
Let's assume we have a URL with a few parameters, https://domain.com/?id=2187&name=Josh&title=Developer
. We can parse those query string parameters with URLSearchParams
:
var params = new URLSearchParams(window.location.search);
Now we have access to each of the individual parameter keys and values, which we can collect with the URLSearchParams.get()
method:
var id = params.get("id");
console.log(id);
// 2187
var name = params.get("name");
console.log(name);
// Josh
var title = params.get("title");
console.log(title);
// Developer
Check for An Existing URL Parameter
You can use the URLSearchParams.has()
method to check whether or not a parameter exists within our query string:
console.log(params.has("id"));
// true
console.log(params.has("company"));
// false
Get All URL Parameters
You can use the URLSearchParams.getAll()
method to return all values associated with a single URL parameter in array format:
console.log(params.getAll("title"));
// ['Developer']
To demonstrate how this works, we'll add a second title parameter value:
params.append("title", "Consultant");
Now, if you use the .getAll()
again, it will return both parameter values in the array:
console.log(params.getAll("title"));
// ['Developer', 'Consultant']
Loop Through URL Parameters
You can also loop through a list of key/value pairs a couple of different ways, providing additional ways to access all of your URL parameters with ease:
var keys = params.keys();
var values = params.values();
var entries = params.entries();
for (var key of keys) {
console.log(key);
}
// id
// name
// title
for (var value of values) {
console.log(value);
}
// 2187
// Josh
// Developer
for (var entry of entries) {
console.log(entry[0], entry[1]);
}
// id: 2187
// name: Josh
// title: Developer
Conclusion
URL parameter parsing and manipulation has never been easier, thanks to JavaScript and the URLSearchParams
interface.
Created: August 21, 2022
Comments
There are no comments yet. Start the conversation!