Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

marked as duplicate by Raymond Chen, jsalonen, EfForEffort, Mark Coleman, Scott Saad Oct 16 '12 at 17:42

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

5  
What have you tried? –  Kuf Oct 15 '12 at 7:43

2 Answers 2

up vote 1 down vote accepted

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...

share|improve this answer
    
Thank you very much. –  user1746349 Oct 15 '12 at 7:51
    
@user1746349 If this answer solved your problem, accept it by clicking the outlined checkmark under the down arrow. –  Daedalus Oct 15 '12 at 7:53
    
The original string looks like a query string from a URI, in which case escaping needs to be handled, too. –  Raymond Chen Oct 15 '12 at 8:16
    
@RaymondChen - Yes, of course. That falls within the "exercise for the reader" category. –  nnnnnn Oct 15 '12 at 8:20

Try this:

JSON.parse('{"' + decodeURI(myString.replace(/&/g, "\",\"").replace(/=/g,"\":\"")) + '"}')
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.