i've been working for some homework in replicating a json parse like function and currently i wrote a function as follows :
var arr = '[a, [a, bjng], n]'
var intoArray = function(string) {
if (string.length <= 2) {
return [];
}
var resultsArr = [];
var toJoin = [];
var simpArr = string.slice(1, string.length - 1).replace(/['"]+/g, '').replace(/[' '']+/g, '').split(',');
for (var a = 0; a < simpArr.length; a++) {
if (simpArr[a].includes('[')) {
while (!simpArr[a].includes(']')) {
toJoin.push(simpArr[a]);
a++;
}
}
if (simpArr[a].includes(']')) {
toJoin.push(simpArr[a]);
}
}
var joined = toJoin.join(',')
var joint = joined.slice(1, joined.length - 1).replace(/['"]+/g, '').replace(/[' '']+/g, '').split(',')
for (var a = 0; a < simpArr.length; a++) {
if (!toJoin.includes(simpArr[a])) {
resultsArr.push(simpArr[a])
}
if (simpArr[a] === toJoin[0]) {
resultsArr[a] = joint
}
}
return resultsArr
};
console.log(intoArray(arr))
when run it converts this string '[a, [a, bjng], n]'(this is all just one big string) into [ 'a', [ 'a', 'bjng' ], 'n' ] (this is an array with multiple string and another array inside, this is the desired behavior). However when the sample string has more than one array inside of it like '[a, [a, bjng],[c] , n]' the result is that it is taken as just one bigger array like [ 'a', [ 'a', 'bjng]', '[c' ], 'n' ] (notice how instead of creating two array it thinks that '[a' trough 'c]' is one big array), i'm still learning so some insight would be much appreciated or if someone has some idea of how i can adapt it to handle multiple arrays!!! or perhaps a better implemntation?