1

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]"]
Abhinav
  • 23
  • 4
  • 3
    Show us what you already have tried. – maximelian1986 Feb 04 '19 at 07:14
  • Have you tried JSON.parse(my_string) ? this will convert into array – TheParam Feb 04 '19 at 07:17
  • That's an invalid JSON string. You're better off fixing where and how that string gets created than play around with `split`, `replace` or some regex – adiga Feb 04 '19 at 07:17
  • @TheParam It's not a valid JSON string. – JLRishe Feb 04 '19 at 07:17
  • @TheParam the input string is not JSON. [JSON](http://json.org) uses double quotes (`"`) to enclose the strings and it encodes a single object. The string posted in the question contains multiple objects separated by comma. – axiac Feb 04 '19 at 07:18
  • Possible duplicate of [How to convert a string with arrays to an array](https://stackoverflow.com/questions/51397094/how-to-convert-a-string-with-arrays-to-an-array) – Adelin Feb 04 '19 at 07:19
  • Why don't you use the JSON syntax? That's exactly what it's made for –  Feb 04 '19 at 07:22

3 Answers3

4

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);
Nick Parsons
  • 38,409
  • 6
  • 31
  • 57
1

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.

Vivek
  • 2,487
  • 1
  • 18
  • 19
0

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]];
Oğuzhan Aygün
  • 139
  • 1
  • 1
  • 13