How can I get a specific parameter from location.search? [duplicate]
If I had a URL such as
http://localhost/search.php?year=2008
How would I write a JavaScript function to grab the variable year and see if it contains anything?
I know it can be done with location.search
but I can’t figure out how it grabs parameters.
Solution 1:
You may use window.URL
class:
new URL(location.href).searchParams.get('year')
// Returns 2008 for href = "http://localhost/search.php?year=2008".
// Or in two steps:
const params = new URL(location.href).searchParams;
const year = params.get('year');
Solution 2:
My favorite way for getting URL params is this approach:
var parseQueryString = function() {
var str = window.location.search;
var objURL = {};
str.replace(
new RegExp( "([^?=&]+)(=([^&]*))?", "g" ),
function( $0, $1, $2, $3 ){
objURL[ $1 ] = $3;
}
);
return objURL;
};
//Example how to use it:
var params = parseQueryString();
alert(params["foo"]);
Solution 3:
A non-regex approach, you can simply split by the character '&' and iterate through the key/value pair:
function getParameter(paramName) {
var searchString = window.location.search.substring(1),
i, val, params = searchString.split("&");
for (i=0;i<params.length;i++) {
val = params[i].split("=");
if (val[0] == paramName) {
return val[1];
}
}
return null;
}
2020 EDIT:
Nowadays, in modern browsers you can use the URLSearchParams
constructor:
const params = new URLSearchParams('?year=2020&month=02&day=01')
// You can access specific parameters:
console.log(params.get('year'))
console.log(params.get('month'))
// And you can iterate over all parameters
for (const [key, value] of params) {
console.log(`Key: ${key}, Value: ${value}`);
}