Page 1 of 1

Javascript location.search into Array.

Posted: Sat Mar 31, 2007 1:51 pm
by JellyFish
How could I take the location.search string and turn it into an array like the php $_GET array?

For example:

location.search equals "?mode=newtopic&f=13"

Code: Select all

_GET = new Array();

_GET['mode'] = "newtopic";
_GET['f'] = 13;
This only more flexible(no fixed naming, values and number of indexes).

I think you'd probably understand what I mean.

Thanks for reading and I'd appreciate any help with this one. :D

Posted: Sat Mar 31, 2007 2:16 pm
by feyd
substring(), split(), array iteration and split() again with some assignments.

Posted: Sat Mar 31, 2007 2:19 pm
by nickvd
Method One: Parse it yourself :)

Method Two:

Code: Select all

function parseQueryString() {
   str = location.search;
   var query = str.charAt(0) == '?' ? str.substring(1) : str;
   var queryString = new Object();
   if (query) {
      var fields = query.split('&');
      for (var f = 0; f < fields.length; f++) {
         var field = fields[f].split('=');
         var fieldName = unescape(field[0].replace(/\+/g, ' '));
         var fieldValue = (field[1])?unescape(field[1].replace(/\+/g, ' ')):'';
         queryString[fieldName] = fieldValue;
      }
   }
   return queryString;
}
Usage:

Code: Select all

 var query = parseQueryString(); //http://example.com/index.php?foo=this&bar=that
alert(query.foo); //this
alert(query.bar); //that

Posted: Sat Mar 31, 2007 3:01 pm
by JellyFish
Thanks both of you.

I'll use your code nickvd only maybe create a _GET global array. :D