Home > OS >  How do I turn this string into an array of numbers?
How do I turn this string into an array of numbers?

Time:10-06

I'm writing this code where a user inputs an array in a input box, so the box pretty much contains a string that looks somewhat like this: [2, 2, 2, 2, 2, 9, 9, 9, 2, 2, 2], [2, 1, 1, 1, 1, 9, 9, 9, 1, 1, 2], [2, 1, 1,14, 1, 9, 9, 9, 1, 1, 2] etc. etc.

I want to convert this into an array of arrays of numbers so that my code can do something with this, but I'm not sure how.

Simply grabbing the value of the input box outputs something like this: '[2, 2, 2, 2, 2, 9, 9, 9, 2, 2, 2], \n[2, 1, 1, 1, 1, 9, 9, 9, 1, 1, 2], \n[2, 1, 1,14, 1, 9, 9, 9, 1, 1, 2]', and when I attempt to split it/regex replace something, either I get nothing, or I get arrays that look like this: ["2, 2, 2, 2, 2, 9, 9, 9, 2, 2, 2"]. I'm not quite sure how to fix this, and the code I am using needs it as numbers.

I don't know what to do, so any ideas would be helpful. Thanks!

CodePudding user response:

You can use JSON.parse:

const str = '[2, 2, 2, 2, 2, 9, 9, 9, 2, 2, 2],     \n[2, 1, 1, 1, 1, 9, 9, 9, 1, 1, 2],     \n[2, 1, 1,14, 1, 9, 9, 9, 1, 1, 2]';

const arrs = JSON.parse('['   str   ']')

console.log(arrs)

  • Related