How to get the value from URL Parameters ?
Hey, Welcome to the tutorial. Today, we will learn How to get URL Parameter values ?geo=UK&size=300×600 in Javascript ?
Video Tutorial
If you are not used to Basics of What is Query String and Parameters ? Learn here before continuing to this tutorial
How to approach the problem ?
We will solve the problem using URL Object, which is basically getting the url of the page when it loads, then passing it though the URL object, like this –
var url = new URL(“https://mrvirk.com?geo=UK&size=300×600”);
Solution Code in Javascript
Follow the code below on Codepen and insert the parameter in codepen url to see results in console.
See the Pen How to get the value from the GET parameters? by Navjot Singh Virk (@virksaabnavjot) on CodePen.
Output
Let’s pass the parameters in the URL, ?geo=UK&size=300×600
Code Explanation
We have 2 options –
Statically Pass the URL
var url_string = “https://mrvirk.com?geo=UK&size=300×600”;
OR
Fetch it from the page URL (recommended)
window.onload = function() {
var url_string = (window.location.href).toLowerCase(); }
In this example, I will be using option 2 and getting URL values when the page loads.
- Firstly, pass the url_string through URL object.
- Then using the searchParams.get and passing the parameter name like – geo
- Output Results – The code will return the parameter value for you.
- Additionally, add try catch for better error handling.
Application of this Tutorial
This article/tutorial is useful if you want to get parameter values, or looking for a solution on how to pass parameter in url in javascript, javascript get url query string, urlsearchparams
Resources
URLSearchParams Documentation – check out more about it and its compatibility with the browsers.