0

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

3
  • your data does not match the one in the code. Commented Mar 15, 2019 at 14:06
  • yes sorry a copy paste mistake Commented Mar 15, 2019 at 14:24
  • You can edit your question to show which is correct, the [true, '3/5', 5] format or the [2010, 1, 2] one. Commented Mar 15, 2019 at 14:27

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

nice thank you one more : How i can sum all the 2 property of all array element without loop ?
2

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 );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.