1

I'm trying to write a Javascript function to get the query string of the browser and allow a new key/value to be passed to the function. If the key exists, I need to replace the value. Since I've spent the last 3.5 hours on this, I haven't yet gotten around to the replacing part.

So far, I'm using the answer here: How to get the query string by javascript? to get the query string. However, it doesn't appear to work... The URL I was testing with was: http://www.site.com/poo?drwho=tombaker&companion=k9

  var assoc  = {}; 
  var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); }; 
  var queryString = location.search.substring(1);  
  var keyValues = queryString.split('&');  

  for(var i in keyValues) {  
     var key = keyValues[i].split('=');  
     assoc[decode(key[0])] = decode(key[1]);  
  }  

  if(assoc["dr"] === undefined ) { 
     // not found. todo: replace
  } 

I'd really appricate any help! Is there any simpler way of doing this using JQuery?

4
  • 2
    What does "doesn't appear to work" mean? Commented Dec 3, 2011 at 0:36
  • As in it does nothing. It says the assoc array is empty. Commented Dec 3, 2011 at 0:43
  • When I try your code and add an alert(assoc["drwho"]); at the end, it outputs "tombaker", just as expected... Commented Dec 3, 2011 at 1:09
  • Tried again using jsFiddle and it works. I was using the W3C one. Commented Dec 3, 2011 at 2:47

2 Answers 2

2

Copy and pasted your code here: http://jsfiddle.net/6KcWh/5/, and added a call to JSON.stringify() to examine the contents of assoc. It turns out assoc is not undefined. But, of course assoc.dr is undefined, because there is no querystring argument of dr. There is a querystring argument of drwho. It looks like you were looking for the wrong querystring argument.

Sign up to request clarification or add additional context in comments.

Comments

1

You appear to be misusing for...in.

Try converting your for loop to a standard for (i = 0 ; i < keyValues.length; i++) and check out some other answers about what for...in is used for in JavaScript.

2 Comments

No misuse here; the "for...in" construct is a proper "for each" loop, javascript syntax
Thanks. Tried it with link and all works. I was using the W3C one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.