Javascript location.search into Array.

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
JellyFish
DevNet Resident
Posts: 1361
Joined: Tue Feb 14, 2006 7:18 pm
Location: San Diego, CA

Javascript location.search into Array.

Post 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
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

substring(), split(), array iteration and split() again with some assignments.
nickvd
DevNet Resident
Posts: 1027
Joined: Thu Mar 10, 2005 5:27 pm
Location: Southern Ontario
Contact:

Post 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
User avatar
JellyFish
DevNet Resident
Posts: 1361
Joined: Tue Feb 14, 2006 7:18 pm
Location: San Diego, CA

Post by JellyFish »

Thanks both of you.

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