views:

75

answers:

4

I can use JavaScript's split to put a comma-separated list of items in an array:

var mystring = "a,b,c,d,e";
var myarray = mystring.split(",");

What I have in mind is a little more complicated. I have this dictionary-esque string:

myvalue=0;othervalue=1;anothervalue=0;

How do I split this so that the keys end up in one array and the values end up in another array?

A: 

I'd still use string split, then write a method that takes in a string of the form "variable=value" and splits that on '=', returning a Map with the pair.

brydgesk
A: 

Split twice. First split on ';' to get an array of key value pairs. Then you could use split again on '=' for each of the key value pairs to get the key and the value separately.

mjh2007
A: 

You just need to split by ';' and loop through and split by '='.

var keys = new Array();
var values = new Array();

var str = 'myvalue=0;othervalue=1;anothervalue=0;';
var items = str.split(';');
for(var i=0;i<items.length;i++){
    var spl = items[i].split('=');
    keys.push(spl[0]);
    values.push(spl[1]);
}

You need to account for that trailing ';' though at the end of the string. You will have an empty item at the end of that first array every time.

Jage
+2  A: 

Something like this:

var str = "myvalue=0;othervalue=1;anothervalue=0;"
var keys = [], values = [];

str.replace(/([^=;]+)=([^;]*)/g, function (str, key, value) {
  keys.push(key);
  values.push(value);
});

// keys contains ["myvalue", "othervalue", "anothervalue"]
// values contains ["0", "1", "0"]

Give a look to this article:

CMS
Now THAT is schmancy.
Jage