Question

I have a string value like:

1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i

I need to convert it into array in JavaScript like

1 2 3

4 5 6 

7 8 9

etc.

Can any one please suggest me a way how to do this?

Was it helpful?

Solution

You are looking for String.split. In your case, you need to split twice. Once with ; to split the string into chunks, then separately split each chunk with , to reach the array structure you are looking for.

function chunkSplit(str) {
    var chunks = str.split(';'), // split str on ';'
        nChunks = chunks.length, 
        n = 0;

    for (; n < nChunks; ++n) { 
        chunks[n] = chunks[n].split(','); // split each chunk with ','
    }

    return chunks;
}

var arr = chunkSplit("1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i");

OTHER TIPS

If you need a multi-dimensional array you can try :

var array = yourString.split(';');

var arrCount = array.length;
for (var i = 0; i < arrCount; i++)
{
  array[i] = array[i].split(',');
}

Try the following:

var yourString = '1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i';
var array = [];
yourString.split(';').forEach(function(value) {
  array.push(value.split(','));
});

The following split command should help:

 yourArray = yourString.split(";");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top