get Query parameters code example
Example 1: javascript read query parameters
// example url: https://mydomain.com/?fname=johnny&lname=depp
const queryString = window.location.search;
console.log(queryString);
// ?fname=johnny&lname=depp
const urlParams = new URLSearchParams(queryString);
const firstName = urlParams.get('fname');
console.log(firstName);
// johnny
const lastName = urlParams.get('lname');
console.log(lastName);
// depp
Example 2: javascript get query parameter
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^]*)');
var results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
Example 3: expressjs query params
// GET /search?q=tobi+ferret
console.dir(req.query.q)
// => 'tobi ferret'
// GET /shoes?order=desc&shoe[color]=blue&shoe[type]=converse
console.dir(req.query.order)
// => 'desc'
console.dir(req.query.shoe.color)
// => 'blue'
console.dir(req.query.shoe.type)
// => 'converse'
// GET /shoes?color[]=blue&color[]=black&color[]=red
console.dir(req.query.color)
// => ['blue', 'black', 'red']
Example 4: query parameters
Query Parameter
represented as key value pair right after the ?
https://www.google.com/search?q=iloveyou
usually used to filter the result
GET /api/spartacus/search?gender=Male&nameContains=li
if we have more than one query parameter
& is used to connect them
Also there is a Path Parameter|variable
/api/spartans/{id} /api/spartans/:id
It's used to identify single resource amonth list of resources
in above example
the id is the path parameter to identify single spartan