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
You can convert URL params to an Object:
const params = location.search.slice(1).split('&').reduce((acc, s) => {
const [k, v] = s.split('=')
return Object.assign(acc, {[k]: v})
}, {})
Then it can be used as a regular JS Object:
params.year // 2008