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 that there is a split function in which i have to specify delimiter.When i did this:-
my_string.split(',');
I got the following result:
["['page1'", "5]", "['page2'", "3]", "['page3'", "8]"]
3 Answers 3
The first thing you should try and do is to make my_string a valid JSON string. That means that instead of single quotes (') you have double quotes (") around your strings. To create a JSON string like this, you can use JSON.stringify() on the data you want to be converted into a string. Below is a valid JSON string of your array which you can use JSON.parse(my_string) on:
const my_string = '[["page1",5],["page2",3],["page3",8]]';
const res = JSON.parse(my_string);
console.log(res);
If you can't do this for whatever reason, then you can try one of the below options.
You can use JSON.parse() and .replace() to make your string a valid JSON string that is parseable 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. Note that you should only use this if my_string is coming from a trusted source (ie: not user input):
const my_string = "['page1',5],['page2',3],['page3',8]";
arr = Function('return [' + my_string + ']')();
console.log(arr);
Comments
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.
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]];
split,replaceor some regex") to enclose the strings and it encodes a single object. The string posted in the question contains multiple objects separated by comma.