The following blog post will teach you how to get URL parameters in JavaScript. You’ll see what the data looks like, and learn some of the different ways you can pull URL arguments out. You can also get the URL without parameters.
Most web applications require the client to pass a parameter or a set of parameters that represent different data. These can be for example username, the search term(s), file names, etc.
Normally these are passed by putting them in the address bar after a question mark (?). For example:
http://mywebpage.com/somepage.html?name=john&role=user
In order to extract these parameters from the URL, we need to parse them. Let’s check how to parse it.
CONTENTS
Get full URL with parameters
In order to get the full URL with parameters from the browser address bar, we can use window.location
object. Let’s check the example below.
//example url is http://example.com/index.php?post_id=5&filter=new
var current_url = window.location.href;
Get query params using URL Object
So, there is no built-in function in JavaScript to get URL parameters by name. You can use the API provided by modern browsers. Let’s check the code below:
//example url is http://example.com/index.php?post_id=5&filter=new
//get the current url
var current_url = window.location.href;
//create a new object
var url = new URL(current_url);
//get post id from url string
var post_id = url.searchParams.get("post_id");
//print the post id
console.log(post_id);
The output will be 5.
Parse URL arguments using regular expression
You can easily parse URL params using regular expressions. Check out the code below:
function getUrlArgument() {
var params = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
params[key] = value;
}
);
return params;
}
console.log( getUrlArgument()["post_id"] );
By using the above code, you can get multiple URL parameters by passing the key name. In the above example, we have passed post_id as key and the above function returned the value 5.
Conclusion
In this blog post, we covered how to get URL parameters in JavaScript. As you can see from the examples given, it’s not difficult at all! We hope that with these tips and tricks under your belt, you’ll be able to solve some of those tricky coding problems more efficiently than before. If you’re still struggling with any questions on getting URL Parameters in JavaScript or want a more detailed guide on using them for different purposes, comment below and I’ll help out as best I can. Happy coding!