[JS] Recupérer QueryString d'une URL
Ancienne méthode
function
getParameterByName(name, url) {
if
(!url) url = window.location.href;
name = name.replace(/[\[\]]/g,
"\\$&"
);
var
regex =
new
RegExp(
"[?&]"
+ name +
"(=([^&#]*)|&|#|$)"
),
results = regex.exec(url);
if
(!results)
return
null
;
if
(!results[2])
return
''
;
return
decodeURIComponent(results[2].replace(/\+/g,
" "
));
}
Utilisation
// query string: ?foo=lorem&bar=&flp
var
foo = getParameterByName(
'foo'
);
// "lorem"
var
bar = getParameterByName(
'bar'
);
// "" (present with empty value)
var
flp = getParameterByName(
'flp'
);
// "" (present with no value)
var
ogr = getParameterByName(
'ogr'
);
// null (absent)
Nouvelle méthode basé sur : URLSearchParams
var
searchParams =
new
URLSearchParams(window.location.search);
//?anything=123
console.log(searchParams.get(
"anything"
))
//123