1

I have a string like this "12,a,{3,4},b,c" , i need to convert it into an array in which the element in curly braces should be a sub array , the result should look like this

["12","a",[3,4],"b","c"]

For other eg:

"12,a,b,c,{e,f}" --> ["12","a","b","c", ["e","f"]]

"{12,a},b,c,{c,d}" --> [["12","a"],"b","c", ["e","f"]]

3
  • Would an array like this be acceptable? [["12"],["a"],["3","4"],["b"],["c"]] That could be expressed as a jagged array of Strings. Oct 29, 2013 at 6:33
  • Yes should be but at last
    – Sarath
    Oct 29, 2013 at 6:38
  • What are you doing this for? Oct 29, 2013 at 6:50

3 Answers 3

1

You can try this code:

a = "{12,a},b,c,{c,d}";
m = a.match(/{[^}]*}|[^,]+/g);
arr=[];

for (i=0; i<m.length; i++) {
    if (m[i].indexOf('{') >= 0)
        arr.push(m[i].replace(/[{}]/g, "").split(/,/));
    else
    arr.push(m[i]);
}
console.log(arr);

OUTPUT:

[[12,a],b,c,[c,d]]
0

could you try this .

var m = "{12,a},b,c,{c,d}".split(','),

result = m.reduce( function( a, b) {

    if ( b.indexOf('{') !== -1 || a.t.length ){
        a.t.push( b.replace(/\{|\}/,'') );
    } else {
        a.array.push( b );
    }

    if ( b.indexOf('}') !== -1 ){
        a.array.push( a.t );
        a.t = [];
    }
    return a ;

}, { array:[],t:[]} ).array;

console.log( result );
0
var a = "12,a,{3,4},b,c,{2,3}";
var b = eval(("[" + a.replace(/{/g, '[').replace(/}/g, ']') + "]").replace(/[a-zA-Z]/g, function (all, match) { return "'" + all+ "'";}));
console.log(b)

Try this

4
  • b is string , i want b as an array
    – Sarath
    Oct 29, 2013 at 6:51
  • a = "12,'a',{3,4},'b','c',{2,3}"; is not possible its "12,a,{3,4},b,c,{2,3}"
    – Sarath
    Oct 29, 2013 at 7:04
  • @rab please explain why eval is bad idea? Oct 29, 2013 at 7:22
  • @Sarath Saleem please check if you got the required answer Oct 29, 2013 at 7:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.