Contents
It is possible in JavaScript to retrieve the parameters of a get parameter from URL. We will rely on the ‘window.location.search’ attribute, which returns the character string containing these parameters.
URL parameters are variables that we will use to transmit information to the website that we will use to process the page. The list of parameters begins in a URL with the ‘the ?’ character. The variables then follow the form variable=value and are separated by the character &.
Get Parameter from URL Example:
//Example url with parameters
http://www.example.com/recherche.php?nom=toto&age=15&ville=london
It is possible in JavaScript to retrieve the parameters of a URL. We will rely on the ‘window.location.search’ attribute, which returns the character string containing the URL parameters.
Once this string has been retrieved, it will be necessary to obtain the attribute’s value according to its name. We know that the name is preceded by the ‘character ?’ or ‘&’, that it is followed by the ‘sign =’, and that the value is then found, followed either by the ‘sign &’, announcing another variable or by the end of the string.
Once the value has been retrieved, we replace the + character with a space (because spaces are transformed into + signs in a URL), and we apply the ‘decodeURIComponent()’ method on the string. This method replaces special characters encoded in a URL with their original form. This is particularly the case for accented characters.
Example:
function getParameterByName(name)
{
name = name.replace(/[[]/, [).replace(/[]]/, ]);
var regexS = [?&] + name + =([^&#]*);
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null)
return ;
else
return decodeURIComponent(results[1].replace(/+/g, ));
}
If you instead want to use a function that directly transforms the parameters of the URL into an associative array, you will have to loop with the ‘search()’ method of the Regex class. This method searches for the next occurrence of a regular expression.
Example:
function getParameters()
{
var urlParams,
match,
pl = /+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, )); },
query = window.location.search.substring(1);
urlParams = {};
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
return urlParams;
}
Getting URL Parameter
In modern browsers this has become much easier thanks to the ‘URLSearchParams’ interface. This defines a set of utility methods for working with a URL’s query string.
Assuming our URL, ‘https://example.com/?product=shirt&color=blue&newuser&size=london’
We can get the query string using.
window.location.search
const queryString = window.location.search;
console.log (queryString);
//? produit = chemise & couleur = bleu & nouvel utilisateur & taille = london
We can then parse the query string parameters using ‘URLSearchParams’. Then we call one of the methods on the result. For example, URLSearchParams.get() returns the first value associated with the given search parameter:
const product = urlParams .get (‘produit’)
console.log (produit);
// shirt
const color = urlParams.get (‘color’)
console.log (couleur);
// blue
const newUser = urlParams.get (‘newuser’)
console.log (newUser);
// empty string
Verifying the Existence of a Parameter
URLSearchParams.has (); to check if a certain parameter exists, you can use:
console.log(urlParams.a(“product”));
// true
console.log(urlParams.has(‘payment method’));
// fake
Getting All Values of a Parameter
URLSearchParams.getAll (); to return all values associated with a given parameter:
console.log(urlParams.getAll(‘Size’));
// [ ‘m’ ]
// Programmatically add a second size parameter.
urlParams. append(‘size’, ‘xl’);
console.log(urlParams.getAll(‘size’));
// [ ‘m’, ‘xl’ ]
Iterating Over Parameters
‘URLSearchParams’ also provides familiar iterator methods that allow you to iterate over Object keys, values and entries:
const
keys = urlParams.keys(),
values = urlParams.values(),
entries = urlParams.entries();
for (const key of keys) console.log(key);
// product, color, new user, size
for (const value of values) console.log(value);
// shirt, blue, m
for (constant input of inputs) {
console.log(`${entry[0]}:${entry[1]}`);
}
// product: shirt
// Color blue
// New user:
// size M
Roll your own query string parser function. Let’s stick with the URL we used in the previous section:
- http://example.com/?product=shirt&color=blue&newuser&size=m
Here is a function that gives you all the URL parameters as a clean object:
function getAllUrlParams(url) {
// get query string from url (optional) or window
var queryString = url? url. split(‘?’)[1]: window. location. search. slice(1);
// we store the settings here
var obj = {};
// if there is a query string
if (queryString) {
// the stuff after # is not part of the query string, so remove it
queryString = queryString. split(‘#’)[0];
// split our query string into its components
var arr = queryString. split(‘&’);
for (var i = 0; i < arr.length; i++) {
// separate keys and values
var a = arr[i].split(‘=’);
// set parameter name and value (use ‘true’ if empty)
var paramName = a[0];
var paramValue = typeof(a[1]) === ‘undefined’? true: a[1];
// (optional) keep case consistent
paramName = paramName.toLowerCase();
if (typeof paramValue === ‘string’) paramValue = paramValue.toLowerCase();
// if the paramName ends in square brackets, e.g. colors[] or colors[2]
if (paramName. match(/[(d+)?]$/)) {
It will help if you read our article, Unblock Youku for Chrome.