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


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


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);
31.03.2017 / 16:34

Another option is to use ()

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

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();
31.03.2017 / 16:43

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


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

31.03.2017 / 18:05

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
var data = "['aaaaa', 'bbbbb', 'ccccc', 'ddddd']";
var array = data.replace("[","").replace("]","").split(",")
31.03.2017 / 16:36

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