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
Anas Abu Farraj
1,5984 gold badges23 silver badges32 bronze badges
asked Mar 15, 2019 at 14:05
Luca Ruggeri
1211 silver badge9 bronze badges
2 Answers 2
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)
answered Mar 15, 2019 at 14:10
epascarello
208k20 gold badges206 silver badges246 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Luca Ruggeri
nice thank you one more : How i can sum all the 2 property of all array element without loop ?
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 );
answered Mar 15, 2019 at 14:14
Shilly
8,5991 gold badge21 silver badges24 bronze badges
Comments
lang-js
[true, '3/5', 5]format or the[2010, 1, 2]one.