-2

I have..

var genre = ["M","F"];

without single quotes and need

["M", "F"]

Not

M,F

With quotes and [ ]; Any idea?

Thanks.

Lenin Che
  • 29
  • 1
  • 4

5 Answers5

3

You could try

var genre = ["M", "F"];
alert(JSON.stringify(genre));
sgbj
  • 2,264
  • 17
  • 14
0
function strToArr( str ) {
    var arr = [];
    if( typeof str === 'string' ) {
        str = str.substring( 1, str.length - 1 );
        arr = str.split( ',' );
    }
    return arr;
}
Yuan Zhaohao
  • 574
  • 5
  • 4
0

I don't how many will like it, but try

var genre = '["M","F"]';
genre = eval(genre )

If you don't like to use eval() then use @YuanZhaohao's answer

Community
  • 1
  • 1
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

If I understood, this will do it:

var str = '["a","b","c"]';

var arr = str.split(/\"]|\["|\","/g).slice(1,-1);

You end up with an array like ["a", "b", "c"]

Note: you might want to do extra checks in case of the possibility of unexpected format like (e.g. with some random spaces '["a", "b" ,"c"]')

ajax333221
  • 11,436
  • 16
  • 61
  • 95
0

If you want a string, try this:

genre = genre.reduce(function(a, b) { return a + '' + b; });
Joe Simmons
  • 1,828
  • 2
  • 12
  • 9