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


I have a string representing an array as follows:

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

I wish I could transform this array that is in the string into an Array to perform manipulations.

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

Thank you in advance.


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

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

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

but yes:

var string = "['aaaaa', 'bbbbb', 'ccccc', 'ddddd']".replace(/'/g, '\"');
var arr = JSON.parse(string);
Scroll to Top