简体   繁体   中英

JavaScript - How to split a string in two dimensional array?

I need to split the string :

"[true,'3/5', 5],[true, '4/5', 5],[true, '5/5', 5],[true, '6/5', 5],[true, '7/5', 5],[true, '8/5', 5]"

In a bi-dimensional array:

[[true, '3/5', 5], [true, '4/5', 5], [true, '5/5', 5], [true, '6/5', 5], [true, '7/5', 5], [true, '8/5', 5]]

I have tried with:

var months = '[2010,1,2],[2010,3,2],[2011,4,2],[2011,3,2]';
var monthArray2d = [];

months.replace(/(\d+)_(\d+)/g, function($0, $1, $2, $3) {
  monthArray2d.push([parseInt($1), parseInt($2), parseInt($3)]);
});

console.log(monthArray2d);

but without success

So use JSON.parse, since your string has '' around the strings, it needs to be changed to "" so a replace statement can handle it. This assumes your data will not have extra quotes in it.

 var str = "[true,'3/5',5],[true,'4/5',5],[true,'5/5',5],[true,'6/5',5],[true,'7/5',5],[true,'8/5',5]" var arr = JSON.parse("[" + str.replace(/'/g, '"') + "]") console.log(arr) 

Since your string is almost valid JSON, I would just change all the single quotes into double quotes, wrap it into an array, then parse the entire structure:

 const source_string = "[true,'3/5',5],[true,'4/5',5],[true,'5/5',5],[true,'6/5',5],[true,'7/5',5],[true,'8/5',5]"; const valid_json = source_string.replace( /'/g, '"' ); const array_wrapped = '[' + valid_json + ']'; const output = JSON.parse( array_wrapped ); console.log( output ); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM