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

1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

The original string looks like a query string from a URI, in which case escaping needs to be handled, too.
@RaymondChen - Yes, of course. That falls within the "exercise for the reader" category.
1

Try this:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.