Alex Guerin
Alex Guerin

Reputation: 2386

Javascript: working with query string

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?

Upvotes: 1

Views: 297

Answers (2)

gilly3
gilly3

Reputation: 91467

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.

Upvotes: 2

Ken Browning
Ken Browning

Reputation: 29091

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.

Upvotes: 1

Related Questions