Bhumi Shah
Bhumi Shah

Reputation: 9476

How to split two dimensional array in JavaScript?

I have string like below:

"test[2][1]"
"test[2][2]"
etc

Now, I want to split this string to like this:

split[0] = "test"
split[1] = 2
split[2] = 1

split[0] = "test"
split[1] = 2
split[2] = 2

I tried split in javascript but no success.How can it be possible?

CODE:

string.split('][');

Thanks.

Upvotes: 1

Views: 2102

Answers (5)

George Pant
George Pant

Reputation: 2117

You can split with the [ character and then remove last character from all the elements except the first.

var str = "test[2][2]";

var res = str.split("[");
for(var i=1, len=res.length; i < len; i++)  res[i]=res[i].slice(0,-1); 

alert(res);

Upvotes: 0

Dropout
Dropout

Reputation: 13866

As long as this format is used you can do

var text = "test[1][2]";
var split = text.match(/\w+/g);

But you will run into problems if the three parts contain something else than letters and numbers.

Upvotes: 0

t1m0n
t1m0n

Reputation: 3431

function splitter (string) {
   var arr = string.split('['),
       result = [];

   arr.forEach(function (item) {
       item = item.replace(/]$/, '');
       result.push(item);
   })

   return result;
}

console.log(splitter("test[2][1]"));

Upvotes: 0

Vincent Biragnet
Vincent Biragnet

Reputation: 2998

you can try : string.split(/\]?\[|\]\[?/)

Upvotes: 0

timolawl
timolawl

Reputation: 5564

Try this:

  1. .replace(/]/g, '') gets rid of the right square bracket.
  2. .split('[') splits the remaining "test[2[1" into its components.

var str1 = "test[2][1]";
var str2 = "test[2][2]";

var split = str1.replace(/]/g, '').split('[');
var split2 = str2.replace(/]/g, '').split('[');

alert(split);
alert(split2);

Upvotes: 1

Related Questions