How to get “GET” request parameters in JavaScript? [duplicate]

Update June 2021:

Today’s browsers have built-in APIs for working with URLs (URL) and query strings (URLSearchParams) and these should be preferred, unless you need to support some old browsers or Opera mini (Browser support).

Original:

All data is available under

window.location.search

you have to parse the string, eg.

function get(name){
   if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
      return decodeURIComponent(name[1]);
}

just call the function with GET variable name as parameter, eg.

get('foo');

this function will return the variables value or undefined if variable has no value or doesn’t exist

Leave a Comment