开发者

How do I divide a complex string into 3 seperate arrays?

Here's where I am:

I started with an array...cleaned it up using 'regex'.

Now I have this...each item has three values

  • mystring = 4|black|cat, 7|red|dog, 12|blue|fish

Here's where I want to be:

I want to end up with three arrays.

I also want to do this without leaving the page...preferably using javascript

I understand the theory, but I'm getting tangled in the syntax.


I'd use John Resig's famous "search and don't replace" method here, it's perfect for it:

var arr1 = [], arr2 = [], arr3 = [],
    mystring = "4|black|cat, 7|red|dog, 12|blue|fish";

mystring.replace(/(\d+)\|([^\|]+)\|([^,]+)/g, function ($0, $1, $2, $3) { 
    arr1.push($1);
    arr2.push($2);
    arr3.push($3);
}); 

Example


You want to use the split() method :

var res = mystring.split(','); //will give you an array of three strings
var subres = res[0].split('|'); //will give you an array with [4, black, cat]

//etc...


Like this?:

var values = mystring.split(',');

var arrays = new Array();

for(var i=0; i < values.length; i++) {
    var parts = values[i].split('|');
    for(var j = 0; j < parts.length;j++) {
        if(!arrays[j]) {
            arrays[j] = new Array();
        }
        arrays[j].push(parts[j]);
    }
}

Will give you an array that contains those three arrays.


   var str = '4|black|cat, 7|red|dog, 12|blue|fish';

   var tmp = str.split(',');

   var firstArray = Array();
   var secondArray = Array();
   var thirdArray = Array();

   for( var i in tmp ){
        var splitted = tmp[i].split('|');
        //alert(true);
        firstArray[i]=splitted[0];
        secondArray[i]=splitted[1];
        thirdArray[i]=splitted[2];
   }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜