function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
Usage
Example URL:
http://www.example.com/index.php?id=1&image=awesome.jpg
Calling getQueryVariable("id") – would return “1”.
Calling getQueryVariable("image") – would return “awesome.jpg”.
Requests = {
QueryString : function(item){
var svalue = location.search.match(new RegExp(“[\?\&]” + item + “=([^\&]*)(\&?)”,”i”));
return svalue ? svalue[1] : svalue;
}
}
//usage
Requests.QueryString(“id”);
Great snippet, but change the curly quotes to double quotes on this one.
Great, concise snippet. It’s worked where I’ve used it. Knowing the vagaries of data on the Web, there’s bound to be some edge case where it breaks, but so far, this 7½ year old nugget of gold is still serving us well!
nice ! thanks.
Great work, this is a really nice bit of coding! As always, keep it up!
You ‘re right
Nice, really helpful thanks!!
Thanks Chris, totally useful script. Soo going to use that today :D
beauty!!!!!!!
Can i remove the .html extension from my website having a windows based hosting?
I dont know if the server has Isapi_rewrite installed
regards
i think that line = return (false) would be create a bug if your url get more than one variable. false can be break a loop and return just first var in your url..
i think that line should be remove..
regards,
nb : pardon me if i wrong :)
I think you might be mis-reading the brackets. After the for loop has searched all of the
vars
(name-value pairs) and hasn’t foundvariable
then this function returns false.Awesome! Thanks very much!
hi my friends sorry if i speak english but i can’t explain in french so
i got this one in one scripte i created it
page.html?nom=28/09/1986&from=hossa&too=hisok
and i want to get the name of variable nom and from and too
i tried many scripts but they don’t work for me
please can you tell me how to do it in javascript
thanks so much
I think that is what this post is about.
Just call the function defined above.
getQueryVariable("nom");
– would return “28/09/1986”.getQueryVariable("from");
– would return “hossa”.getQueryVariable("too");
– would return “hisok”.I wanted to use this in CoffeeScript if you want to copy and paste this worked for me
getQueryVariable = (variable) ->
query = window.location.search.substring(1)
tabs is all screwed up
Added another if statement to check for space characters ‘%20’ in the parameters
}
Oops I forgot ‘ != -1 ‘ Sorry about that. Here is the correct code:
}
does anyone have a link to an actual live form where something like this has been implemented that I could look at as an example? Sorry I am not very experienced with javascript and having a lot of trouble figuring out how to set this up. I think I am doing something really basic wrong but I can’t figure out what.
Hey Kat. I made a Codepen implementing the code above.
http://codepen.io/anon/pen/ympzk?fname=kat
Hey Chris,
URL Decoding the parameters would be necessary if I’m not mistaken.
Check this solution here: http://stackoverflow.com/a/901144
I am passing a query via the url (http://www.mywebsite.com/appointment-map.aspx?search=33612) and I want to use that query object in the following (urlsearch) and can’t seem to make it work.
In addition to Robert Galindo’s code:
Now we can get more data after the first %20, I mean, all data with spaces, like
uri.html?data=more%20than%20one%20space
I found this info at stackoverflow.com about speeds on “split” and “regex”:
Regards.
Also, as Relfor said, using decodeUriComponent we haven’t to look for spaces (%20) or another symbols (like accents). Less lines of code, better results:
Regards.
Nice Works! God bless my friend
A functional approach (:P):
Even better, don’t do the work once for each query string parameter.
How about combain this function with if/else?
Example:
U have this url
www.domain.com?id=1234&img=test.jpg
Condition
If id=xxxx, then do blablabla, else other.
What script i can use to declare that condition?
Please help. Thanks…
i need YOUR help for check the last 3 char in the URL.
EX:
http://www.google.com
must check last 3 char that is start from dot(.).
EX:
http://www.domainname.xxx
if wrong last 3 char it should move to any alert msg page. Plz help me
can anyone please explain me how to rewrite url using jquery.
Description:
i want rewrite the url by removing the folder path from it.
currently am using asp.net routing which is costly process ,so it would be a great help if any one can give solution for this.
example: products/cloths/jeans.aspx has to be rewritten as jeans.aspx
thanks in advance.
Implemented the original code and id does return the url variable value if the variable exists, else it returns false. The false returned when the variable does not exist is not a string value but, I assume, a javascript boolean? My question is how can I test for the false return, and then take an action? I want to verify that a selection was made that passes a value in the query string, and if not, give the user a message. Thanks for any help.
Hey guys! Great piece of code! Could you tell me how to get current tab url if I am running this code on background page? Any idea if I want to call this code from context menu?
You can get an array of items representing the query params using:
array = location.search.match(/\w+(.=)?\w*/gi)
you can get something like and you can map to an object very easily
[“app_id”, “123”, “appcode”, “123”]
This may be a silly question, but I notice the line
return (false)
How is this different from the more usual
return false
(no brackets)?good code, but it doesn’t work if you’re looking for first element.
Calling getQueryVariable(“id”) – should return “1”. But it doesn’t.
i should clarify. I modified the function to take a url string.
function getQueryVariable(url, variable)
{
var query = url;
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
Thanks !!
Here’s a simple regex code that I’m using:
Source: http://mycodingtricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/
Great work! but what if I have a query string like in the URL below ?
This will send “John” instead of the expected “John & James” …. Just a thought.
If your value has a “&” in it then you’ve got a malformed value. You have to url encode them. In a url query “&” means to start the next var.
Thanks for your helpful post (:
What if i want to return default value?
For example:
http://www.example.com/index.php?id=1&image=awesome.jpg
Calling getQueryVariable(“id”) – would return “1”.
Calling getQueryVariable(“image”) – would return “awesome.jpg”.
What if:
http://www.example.com/index.php
I still want to return “id” value = “predefined value”
Hi there,
Could anyone show me exactly how to apply this in html? I have almost no experience with JS. I have tried dozens of iterations and checked many sites and I’m at my wits end.
My query string at the end of the url is ?foo=jim. I have the JS function inside inside the document head.
I need ‘jim’ to be inserted as a value of a hidden input field. Below is one of the many iterations I have tried to get this to work.
Can anybody let my know exactly where I’m going wrong here?
Many thanks,
Amber
Hi Amber,
I have the same problem as you mentioned in this post and I am wondering if you came up with a solution yet?
@joe – Just change your line :
var query = url; </div>
to :
var query = url.split('?')[1];
This will split out the query part of the url.
Awesome.
I had already a youtube url and just needed the video id.
I found this very nice solution:
Create a link, set href and now you can use ‘location.search’ too.
So I just added this to the function above.
This should be working on older browser too. Not tested by myself, but should work till IE 5.5
This technique only returns “false” when setup exactly like described.
link setup: /test.html?id=1&image=awesome.jpg
Thank you so much! This is great
I got this from MDN: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
window.location is not set for arguments in tags.
Let’s assume you only need to pass arguments without names, just like function calls.
In HTML:
Then, in JavaScript:
Now args contains the array [‘a’,’b’], assuming synchronous script calls.
Usage:
URL = https://css-tricks.com/snippets/javascript/get-url-variables/?a=b&c=&d
urlParams() // {a: ‘b’, c: ”, d: ”}
urlParams(‘a’) // ‘b’
urlParams(‘b’) // null
urlParams(‘c’) // ”
urlParams(‘d’) // ”
Given it some thought and figured this is more concise while achieving the same result.