JavaScript URL variables

Today I needed to get the value of a URL variable in JavaScript. Unlike ColdFusion, in JavaScript there isn't a built-in scope that contains all of your URL variables. You have to manually parse the URL and split the name value pairs. Here is a function I use for this purpose:

function getURLVar(urlVarName) {
//divide the URL in half at the '?'
var urlHalves = String(document.location).split('?');
var urlVarValue = '';
if(urlHalves[1]){
//load all the name/value pairs into an array
var urlVars = urlHalves[1].split('&');
//loop over the list, and find the specified url variable
for(i=0; i<=(urlVars.length); i++){
if(urlVars[i]){
//load the name/value pair into an array
var urlVarPair = urlVars[i].split('=');
if (urlVarPair[0] && urlVarPair[0] == urlVarName) {
//I found a variable that matches, load it's value into the return variable
urlVarValue = urlVarPair[1];
}
}
}
}
return urlVarValue;   
}

So, in ColdFusion I would do this to get a URL variable:

<cfset lastTabVisted = url.lastTab>
and now with this JavaScript function I can do this:
var lastTabVisted = getURLVar('lastTab');

Comments
Hey Jake, Like you I prefer Coldfusion - it's just so much easier. I've been looking for a javascript that will do what you described. I have slew of URL variables and I need to extract one from that URL then output it. I'm not that great with javascripting and I'm trying to adapt your code but I can't figure out how to make it display just the one variable on my page. I tried adding under the return urlVarValu; } {document.write(getURLVar('startdate');} and nothing displays on the page. Can you give me a push in the right direction? Thanks, Wendy
# Posted By Wendy | 10/4/07 9:02 AM
Try putting your document.write statement somewhere else in your code. If I understand right, you are actually putting it inside the getURLVar function, which will not work.
# Posted By Jake Munson | 10/4/07 9:16 AM
I know this is real anal, but you forgot to var i in the loop condition;

for(i=0; i<=(urlVars.length); i++){
should be:
for(var i=0; i<=(urlVars.length); i++){

In anycase, thanks for the function, it'll come in real handy.

[PHP is for fart-huffers and ColdFusion gets you laid]
# Posted By SigmaProjects | 10/30/07 12:55 PM
I wanted to contribute to your function, didnt want to come across case sensitive problems:

function getURLVar(urlVarName) {
   var urlHalves = String(document.location).toLowerCase().split('?');
   var urlVarValue = '';
   if(urlHalves[1]){
      var urlVars = urlHalves[1].split('&');
      for(var i=0; i<=(urlVars.length); i++){
         if(urlVars[i]){
            var urlVarPair = urlVars[i].split('=');
            if (urlVarPair[0] && urlVarPair[0] == urlVarName.toLowerCase()) {
               urlVarValue = urlVarPair[1];
            }
         }
      }
   }
   return urlVarValue;
}
# Posted By SigmaProjects | 10/30/07 2:21 PM
Just a quick note about the case sensitive contribution of SigmaProjects:

Your update even did a lowercase to the content of the variable. So this update will be better:

function getURLVar(urlVarName) {
var urlHalves = String(document.location).split('?');
var urlVarValue = '';
if(urlHalves[1]){
var urlVars = urlHalves[1].split('&');
for(var i=0; i<=(urlVars.length); i++){
if(urlVars[i]){
var urlVarPair = urlVars[i].split('=');
if (urlVarPair[0] && urlVarPair[0].toLowerCase() == urlVarName.toLowerCase()) {
urlVarValue = urlVarPair[1];
}
}
}
}
return urlVarValue;
}

Greetz,

Karim
# Posted By Karim | 12/17/07 2:25 PM
For a minute I thought that we should rename this blog to HowToOvercomplicateSimpleThings.com. Maybe I'm missing something here. If the goal is to work with the value of a URL variable in JavaScript then look no further.

<InvalidTag>
   
   function showEntry(recordAction) {
      if (recordAction == 'Update') {
         var selectedBillingJournalID = ColdFusion.getElementValue('gridBillingJournalEntry','frmBillingJournal','BillingJournalID');
         var selectedBillingBatchID = ColdFusion.getElementValue('gridBillingJournalEntry','frmBillingJournal','BillingBatchID');
      }
      else if (recordAction == 'Create') {
         var selectedBillingJournalID = '';
         var selectedBillingBatchID = <cfoutput>#URL.billingBatchID#</cfoutput>;
      }
      
      day = new Date();
      var windowID = 'trust' + day.getTime();               
      var windowOptions = new Object();
      windowOptions.width = 840;
      windowOptions.height = 500;
      windowOptions.center = true;
      windowOptions.modal = true;
      windowOptions.resizeable = true;
      windowOptions.initshow = true;
      windowOptions.draggable = true;
      windowOptions.closeable = true;
      windowOptions.headerstyle = 'font-family: verdana; background-color: #0066FF;';
            
      ColdFusion.Window.create(windowID,'Billing Journal Entry','editbillingjournalentry.cfm?billingBatchID=' + selectedBillingBatchID + '&billingJournalID=' + selectedBillingJournalID + '&runMode=' + recordAction, windowOptions);
   }      
   
</script>

Did you see me grab the value of the URL variable right in the JavaScript code using a simple cfoutput - look at the else? Yes before someone mentions it there is an IsDefined test on this in a different part of the page. By the way, the JavaScript function does look nice and I can see where it could come in handy, but if your goal was as stated...
"Today I needed to get the value of a URL variable in JavaScript. "
then what I've got here would've done the trick.

Am I missing something here?
# Posted By Andy Sandefer | 3/18/08 7:38 AM
Andy,

What if you don't want to pass your JavaScript through the CF server? In my case, I never put the JS code directly in my pages, I put it in .js files and then pull those into each page as needed. So my JS code is never parsed by the CF server.
# Posted By Jake Munson | 3/18/08 10:15 AM
Yep - you're right Jake - that does make sense.
# Posted By Andy Sandefer | 3/31/08 10:48 AM
Only a complete nob end would have such a small font for their code.
# Posted By George Galloway | 6/14/08 9:34 PM
Or somebody with better eyes than you.
# Posted By Jacob Munson | 6/15/08 12:12 PM
i'm just a fart-huffer (thanks Sigma), but i'm running into a confusing error with this script. i've searched and came across a handful of similar scripts and all are breaking in the same spots:

1) the .split('&') should be replaced with .split('&amp;') or .split('%26')
2) and here's where i get stuck:

in the for loop, i'm getting an "XML Parsing Error: not well-formed" message pointing to the '<=' operator. am i the only one who's running into this issue?
# Posted By T | 7/3/08 5:41 PM
solved:

the problem i was running into can be explained [url=http://javascript.about.com/library/blxhtml.htm]here[/url] (http://javascript.about.com/library/blxhtml.htm)

i didn't have the CDATA tag. i guess i really am a fart-huffer :|
# Posted By T | 7/3/08 7:01 PM
T,

I'm glad you got it solved.
# Posted By Jacob Munson | 7/3/08 8:07 PM
this is a good idea but the proper way would be doing this:

(function(){ // Import GET Vars :D
   document.getVars = [];
   var urlHalves = String(document.location).split('?');
   if(urlHalves[1]){
      var urlVars = urlHalves[1].split('&');
      for(var i=0; i<=(urlVars.length); i++){
         if(urlVars[i]){
            var urlVarPair = urlVars[i].split('=');
            document.getVars[urlVarPair[0]] = urlVarPair[1];
         }
      }
   }
})();

now you can access your getvars by going through the document object:

document.getVars.varname
# Posted By Chad Scira | 8/13/08 1:30 PM
i've never been to a cold fusion site that didn't give me issues or just plain suck.

good example: myspace vs facebook...
# Posted By brandon | 8/25/09 10:08 AM
@bradon,

There are tons of good ColdFusion based sites out there. MySpace just happens to be one of the most high profile sites, and it does suck. But don't judge the entire CF community by MySpace. MySpace is run by "fly the seat of your pants" programmers. And you will find these kinds of sites written in all programming languages.
# Posted By Jake Munson | 8/25/09 10:14 AM
Hi. Hope that this may be helpful in URL parsing by Javascript. Find the source here http://with-love-from-siberia.blogspot.com/2009/07...
# Posted By ildar | 9/22/09 7:37 PM
BlogCFC was created by Raymond Camden. This blog is running version 5.9. Contact Blog Owner