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?

Andreas Köberle
112k58 gold badges281 silver badges308 bronze badges
asked Jan 6, 2012 at 10:54
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");
answered Jan 6, 2012 at 11:05
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(',');
}
answered Jan 6, 2012 at 11:04

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(','));
});
kapa
78.9k21 gold badges166 silver badges178 bronze badges
answered Jan 6, 2012 at 11:03

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(";");
answered Jan 6, 2012 at 10:58

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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.