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.

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

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

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.

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

Comments

Your Answer

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.