-1

How to split a string and breaking it to an array?

I have an string as shown below

1234,1243,"555,552,553"

Using JavaScript, what is the fastest way to split the string and achieve below array

['1234','1243','555,552,553']

  • Try to find a library for parsing CSV files, it will have code that processes quotes like this. – Barmar May 22 '23 at 15:54
  • 1
    If it is just that string a quick hacky way would be `const arr = JSON.parse(\`[${str}]\`);` But I wouldn't recommend it. Barmar's suggestion to look into CSV parsing is far more robust. – pilchard May 22 '23 at 15:57

1 Answers1

-1

You need to use a regex i thinks, maybe there are better way, but it's need to iterate multiple time.

const str = '1234,1243,"555,552,553"';
const regex = /"[^"]+"|[^,]+/g;

const result = str.match(regex).map((item) => item.replace(/"/g, ''));

The result is -> array(3) ['1234', '1243', '555,552,553']

Raphael Rlt
  • 405
  • 2
  • 11