Skip to content

Instantly share code, notes, and snippets.

@williammalo
Forked from 140bytes/LICENSE.txt
Last active March 8, 2018 11:52
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save williammalo/2698303 to your computer and use it in GitHub Desktop.
Save williammalo/2698303 to your computer and use it in GitHub Desktop.
get query variable

use like this:

getQueryVariable("foo")

To get variables in urls eg:

http://foo.com/index.html?foo=bar

If you want to support arrays, check the version by @atk below:

function(a){
return RegExp("[&?]"+a+"=([^&]+)").exec(location)[1]
}
//searches the url (location)
//finds the text after a "&" or a "?" followed by the variable name, followed by a "="
//and before another "&"
function(a){return RegExp("[&?]"+a+"=([^&]+)").exec(location)[1]}
//If you want to support arrays (Thanks atk!)
function(a){for(var b=[],c,d=eval('/[&?]'+a+'(\\[])?=([^&]+)/g');c=d.exec(location);)b.push(c[2]);return b}
{
"name": "getQueryVariable",
"description": "Get variables in urls",
"keywords": [
"url",
"query",
"string",
"variable",
"get"
]
}
<script>
getQueryVariable = function(a){return RegExp("[&?]"+a+"=([^&]+)").exec(location)[1]}
document.write(getQueryVariable("foo"))
</script>
@atk
Copy link

atk commented May 22, 2012

Only 1 char longer:
function(a){for(var b=[],c,d=eval('/[&?]'+a+'(\\[])?=([^&]+)/g');c=d.exec(location);)b.push(c[2]);return b}

@williammalo
Copy link
Author

@atk
Great! it works perfectly! (I think...)
I'll put it in my gist!
Thanks!

@onhate
Copy link

onhate commented Nov 20, 2013

If you have an anchor on url like param=value#anchor it returns the value like value#anchor, you just need to add one more byte to the code to works =D

function url(a){for(var b=[],c,d=eval('/[&?]'+a+'([])?=([^&^#]+)/g');c=d.exec(location);)b.push(c[2]);return b}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment