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
Bhumi Shah
9,50210 gold badges69 silver badges110 bronze badges
5 Answers 5
Try this:
.replace(/]/g, '')gets rid of the right square bracket..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
you can try :
string.split(/\]?\[|\]\[?/)
answered Apr 19, 2016 at 9:55
Vincent Biragnet
3,01817 silver badges22 bronze badges
Comments
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
t1m0n
3,4411 gold badge20 silver badges22 bronze badges
Comments
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
Dropout
14k10 gold badges60 silver badges112 bronze badges
Comments
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
George Pant
2,1171 gold badge11 silver badges15 bronze badges
Comments
lang-js