-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,214
  • 15
  • 13
0
function strToArr( str ) {
    var arr = [];
    if( typeof str === 'string' ) {
        str = str.substring( 1, str.length - 1 );
        arr = str.split( ',' );
    }
    return arr;
}
Yuan Zhaohao
  • 544
  • 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
  • 376,738
  • 64
  • 519
  • 520
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,086
  • 15
  • 58
  • 93
0

If you want a string, try this:

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