How do I transform an array that is in a string to array in javascript?

9

I have a string representing an array as follows:

var = "['aaaaa', 'bbbbb', 'ccccc', 'ddddd']";

I want to be able to transform this array that is in the string into an Array to perform manipulations.

var = ['aaaaa', 'bbbbb', 'ccccc', 'ddddd'];

Thank you in advance.

    
asked by anonymous 31.03.2017 / 16:27

6 answers

7

This string you have looks like a JSON, a representation in String of an array, so you can use JSON.parse() to transform it into an array.

There is however a problem ... ' is not valid as a string separator in JSON, so you can not use

var arr = JSON.parse("['aaaaa', 'bbbbb', 'ccccc', 'ddddd']");

but rather:

var string = "['aaaaa', 'bbbbb', 'ccccc', 'ddddd']".replace(/'/g, '\"');
var arr = JSON.parse(string);
console.log(arr);
    
31.03.2017 / 16:34
5

Another option is to use Array.prototype.map ()

var a = "['aaaaa', 'bbbbb', 'ccccc', 'ddddd']";
var array = a.replace(/['\[\] ]/g,'').split(',').map(String);
console.log(array);

If you want to remove white space at the beginning of the string

var a = "['Carro Azul', 'Carro Vermelho', 'ccccc', 'ddddd']";
var array = a.replace(/['\[\]]/g,'').split(',').map(function (str) {
   return str.trim();
});
console.log(array);
    
31.03.2017 / 16:43
5

Just one more alternative:

var array = "['aaaaa', 'bbbbb', 'ccccc', 'ddddd']";
array = new Function("return " + array)(); // cria uma função retornando o array e a executa

console.log(array);

In this way whatever the content of array , the parse will be done.

    
31.03.2017 / 18:05
2

You can use JSON.parse to resolve this, but in the format that is not going to work directly, the values should be enclosed in double quotes.

In this case you could then do the following:

//Essa parte converte as aspas simples para aspas duplas
var str = "['aaaaa', 'bbbbb', 'ccccc', 'ddddd']";
str     = str.replace(/\'/g,'"');

//Essa parte converte a string em um objeto
var arr = JSON.parse( str );
    
31.03.2017 / 16:45
1
var data = "['aaaaa', 'bbbbb', 'ccccc', 'ddddd']";
var array = data.replace("[","").replace("]","").split(",")
    
31.03.2017 / 16:36
0

You can use JSON.parse (), but by default json's string values use "instead of", this would convert the string to "

var arr = JSON.parse('["aaaaa", "bbbbb", "ccccc", "ddddd"]');
    
31.03.2017 / 16:36