-3

Possible Duplicate:
Parse query string in JavaScript

I want to create an options array from a string. How can i create an array as

{
    width : 100, 
    height : 200
}

from a string like

'width=100&height=200'

Is there to create such arrays?

Community
  • 1
  • 1

2 Answers2

1

Try this:

JSON.parse('{"' + decodeURI(myString.replace(/&/g, "\",\"").replace(/=/g,"\":\"")) + '"}')
Pulkit Goyal
  • 5,365
  • 1
  • 25
  • 48
1

That's not an array, it's an object. It's not multidimensional either.

But anyway, you can split the string on the & separator and then split each item on the =:

var input = 'width=100&height=200',
    output = {},
    working = input.split("&"),
    current,
    i;

for (i=0; i < working.length; i++){
    current = working[i].split("=");
    output[current[0]] = current[1];
}

// output is now the object you described.

Of course this doesn't validate the input string, and doesn't cater for when the same property appears more than once (you might like to create an array of values in that case), but it should get you started. It would be nice to encapsulate the above in a function, but that I leave as an exercise for the reader...

nnnnnn
  • 138,378
  • 23
  • 180
  • 229