Skip to content Skip to sidebar Skip to footer

Convert String Into An Array Of Arrays In Javascript

I have a string as follows: my_string = '['page1',5],['page2',3],['page3',8]'; I want to convert this into the following: my_array = [['page1',5],['page2',3],['page3',8]]; I know

Solution 1:

You can use JSON.parse() and .replace() to make your string a parsable string like so:

const my_string = "['page1',5],['page2',3],['page3',8]",
stringified = '['+my_string.replace(/'/g, '"')+']';

console.log(JSON.parse(stringified));

Or you can use a Function constructor to "loosly" parse your JSON:

const  my_string  = "['page1',5],['page2',3],['page3',8]";
arr = Function('return [' +  my_string + ']')(); 

console.log(arr);

Solution 2:

You can use the eval() function to convert your string to an array. See the code below.

my_string = "['page1',5],['page2',3],['page3',8]";

my_array = eval(`[${my_string}]`);

console.log(my_array);

However, using the eval() function comes with a set of drawbacks if not used properly. Please read through this answer before using eval in any of your serious code.

Solution 3:

first split the string with "],[" and you got an array like bellow

splitted_string = ["[page1,5", "[page2,3" , "[page3,8"];

then loop this array and get rid of "[" character and you got an array like bellow

splitted_string = ["page1,5", "page2,3" , "page3,8"];

finally loop this array and split the each element with ",". viola! you got what you want like bellow

splitted_string =  [['page1',5],['page2',3],['page3',8]];

Post a Comment for "Convert String Into An Array Of Arrays In Javascript"