Kodeclik Blog
Getting URL parameters with Javascript
Most (large) websites allow you to not only access webpages but also support URL parameters, which is a way to add extra information to a website's URL. They are like tags that help the website understand what you want to see or do. The information in the tag tells the website that you want it to search for particular pages or retrieve specific information.
URL parameters are added to the end of a URL after a question mark (?). They are made up of key-value pairs, separated by an equals sign (=). For instance if you are using an library web site, it might support URL parameters such as “book=HarryPotter”. (This is an example, which URL parameters a site supports is dependent on the site.) For instance, if the website URL is “https://mylibrary.com”, then the full URL with URL parameters will be: “https://mylibrary.com?book=HarryPotter”. Some websites allow multiple parameters which are usually separated by an ampersand (&), e.g., “https://mylibrary.com?book=HarryPotter&year=2010”.
URL parameters can be used to filter and organize content on a website, or to pass information between pages. They can also be used for tracking, to see how many people are visiting a website or clicking on a link.
An example of passing URL parameters to a real website can be seen in Wikipedia. We can construct the following URL: https://en.wikipedia.org/w/index.php?title=Sun where the parameter key is “title” and the value is “Sun”. If you type this URL into a browser, you will retrieve the Wikipedia webpage for Sun, like so:
Now, if you would like to process such URLs inside your Javascript program and extract out those key and value pairs, you can write code such as:
let params =
new URL("https://en.wikipedia.org/w/index.php?title=Sun").searchParams;
let myValue = params.get("title");
console.log(myValue);
In the above code, we are using the URL interface which returns a URLSearchParams object that allows access to the GET decoded query arguments contained in the URL. The second line extracts the parameter called “title” and then prints its value to the console. The output will be:
Sun
Another way to use this functionality is in the code below:
const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('myParam');
console.log(myParam);
Here we are using window.location.search to access the current URL and constructing a URLSearchParams object with it. Then we are using get to extract the value associated with the “myParam” key. To illustrate this code with a real site, if the current URL is "https://www.example.com/?myParam=hello" the above code will log "hello" to the console. This is often useful if you need to analyze the current URL and do something different depending on the URL parameters.
URL parameters are very often used with websites that expose an API for public usage. For instance, consider the National Weather Service (NWS) API which allows developers to access critical forecasts, alerts, and observations, along with other weather data. The API is based on JSON-LD and is designed with a cache-friendly approach that expires content based on the information life cycle. To use the NWS API, you can use the following URL with the appropriate parameters:
https://api.weather.gov/points/{latitude},{longitude}
Here, "latitude" and "longitude" are variables denoting the latitude and longitude coordinates of the location you want to get weather data for. For example, to get weather data for Washington, DC you could use the following URL:
https://api.weather.gov/points/38.8898,-77.0091
because (38.8898, -77.0091) are the latitude and longitudes of Washington DC. This particular URL (because it is an API) returns a JSON object, so you will see this on your browser:
{
"@context": [
"https://geojson.org/geojson-ld/geojson-context.jsonld",
{
"@version": "1.1",
"wx": "https://api.weather.gov/ontology#",
"s": "https://schema.org/",
"geo": "http://www.opengis.net/ont/geosparql#",
"unit": "http://codes.wmo.int/common/unit/",
"@vocab": "https://api.weather.gov/ontology#",
"geometry": {
"@id": "s:GeoCoordinates",
"@type": "geo:wktLiteral"
},
"city": "s:addressLocality",
"state": "s:addressRegion",
"distance": {
"@id": "s:Distance",
"@type": "s:QuantitativeValue"
},
"bearing": {
"@type": "s:QuantitativeValue"
},
"value": {
"@id": "s:value"
},
"unitCode": {
"@id": "s:unitCode",
"@type": "@id"
},
"forecastOffice": {
"@type": "@id"
},
"forecastGridData": {
"@type": "@id"
},
"publicZone": {
"@type": "@id"
},
"county": {
"@type": "@id"
}
}
],
"id": "https://api.weather.gov/points/38.8898,-77.0091",
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
-77.0091,
38.8898
]
},
"properties": {
"@id": "https://api.weather.gov/points/38.8898,-77.0091",
"@type": "wx:Point",
"cwa": "LWX",
"forecastOffice": "https://api.weather.gov/offices/LWX",
"gridId": "LWX",
"gridX": 98,
"gridY": 71,
"forecast": "https://api.weather.gov/gridpoints/LWX/98,71/forecast",
"forecastHourly": "https://api.weather.gov/gridpoints/LWX/98,71/forecast/hourly",
"forecastGridData": "https://api.weather.gov/gridpoints/LWX/98,71",
"observationStations": "https://api.weather.gov/gridpoints/LWX/98,71/stations",
"relativeLocation": {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
-77.017229,
38.904103
]
},
"properties": {
"city": "Washington",
"state": "DC",
"distance": {
"unitCode": "wmoUnit:m",
"value": 1739.0633969488
},
"bearing": {
"unitCode": "wmoUnit:degree_(angle)",
"value": 156
}
}
},
"forecastZone": "https://api.weather.gov/zones/forecast/DCZ001",
"county": "https://api.weather.gov/zones/county/DCC001",
"fireWeatherZone": "https://api.weather.gov/zones/fire/DCZ001",
"timeZone": "America/New_York",
"radarStation": "KLWX"
}
}
As you can see the returned JSON clearly labels the result as Washington DC. But note that in this case, the URL does not follow the key=value convention. Because it is a formal API, it has a specific convention to call it (which again we need to be aware of).
In summary, URL parameters are a way to add extra information to a website's URL, which can be used to filter and organize content, send some small details from the client (browser) to the server, pass information between pages, or track user activity. They can contain all kinds of useful information, such as search queries, catalog details, product categories, and more.
If you liked this blogpost, learn how to download a file using Javascript.
Want to learn Javascript with us? Sign up for 1:1 or small group classes.