1

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.

asked Apr 19, 2016 at 9:48
0

5 Answers 5

1

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);

answered Apr 19, 2016 at 9:52
Sign up to request clarification or add additional context in comments.

Comments

0

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

answered Apr 19, 2016 at 9:55

Comments

0

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]"));

answered Apr 19, 2016 at 9:56

Comments

0

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.

answered Apr 19, 2016 at 9:57

Comments

0

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);
answered Apr 19, 2016 at 10:21

Comments

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.