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
-
3Google for "Javascript Split"karim79– karim792012年01月06日 10:55:55 +00:00Commented Jan 6, 2012 at 10:55
-
1do you mean multidimensional array?redmoon7777– redmoon77772012年01月06日 11:00:57 +00:00Commented Jan 6, 2012 at 11:00
-
here's a previous answer that may help stackoverflow.com/questions/5163709/…mrmo123– mrmo1232012年01月06日 11:08:40 +00:00Commented Jan 6, 2012 at 11:08
4 Answers 4
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
nikc.org
17k7 gold badges53 silver badges84 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
jack blank
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 loopIf 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
Elorfin
2,4972 gold badges28 silver badges50 bronze badges
Comments
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(','));
});
- jsFiddle Demo
- Note:
.forEach()not supported in IE <=8
kapa
78.9k21 gold badges166 silver badges178 bronze badges
answered Jan 6, 2012 at 11:03
Rich O'Kelly
41.8k9 gold badges87 silver badges114 bronze badges
2 Comments
nikc.org
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.nikc.org
Might be worth mentioning that
Array.forEach does not have universal browser support. kangax.github.com/es5-compat-table The following split command should help:
yourArray = yourString.split(";");
answered Jan 6, 2012 at 10:58
labrassbandito
53512 silver badges27 bronze badges
1 Comment
pimvdb
Note that there are also commas. It looks like the OP wants to split the results again to get a two-dimensional array.
lang-js