2

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?

3
  • 3
    Google for "Javascript Split" Commented Jan 6, 2012 at 10:55
  • 1
    do you mean multidimensional array? Commented Jan 6, 2012 at 11:00
  • here's a previous answer that may help stackoverflow.com/questions/5163709/… Commented Jan 6, 2012 at 11:08

4 Answers 4

3

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");
Sign up to request clarification or add additional context in comments.

1 Comment

what exactly is the first ";" for in the line for (; n < nChunks; ++n) {? is that there to find the character ";". I am asking because I usually see some sort of expression before the ";" in a for loop
1

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(',');
}

Comments

1

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(','));
});

2 Comments

This does NOT work. Did you even try running your code? The value of split in your for...in loop is the index in the array, not the value.
Might be worth mentioning that Array.forEach does not have universal browser support. kangax.github.com/es5-compat-table
-1

The following split command should help:

 yourArray = yourString.split(";");

1 Comment

Note that there are also commas. It looks like the OP wants to split the results again to get a two-dimensional array.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.