Thursday, October 18, 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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...