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. Commented Oct 29, 2013 at 6:33
  • Yes should be but at last Commented Oct 29, 2013 at 6:38
  • What are you doing this for? Commented 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]]
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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 Comments

b is string , i want b as an array
a = "12,'a',{3,4},'b','c',{2,3}"; is not possible its "12,a,{3,4},b,c,{2,3}"
@rab please explain why eval is bad idea?
@Sarath Saleem please check if you got the required answer

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.