Thursday, 18 October 2018

javascript - How can I get a specific parameter from location.search?

This question is old and things have evolved in JavaScript.
You can now do this:


const params = {}
document.location.search.substr(1).split('&').forEach(pair => {
[key, value] = pair.split('=')
params[key] = value
})

and you get params.year that contains 2008.
You would also get other query params in your params object.




Edit: a shorter/cleaner way to do this:


const params = new Map(location.search.slice(1).split('&').map(kv => kv.split('=')))

You can then test if the year param exists with:


params.has('year')  // true

Or retrieve it with:


params.get('year')  // 2008

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...