Search code examples
javascriptnode.jsregexreplacestring-parsing

How do I parse a string with brackets into array of arrays?


I am receiving a string with brackets already in it and need to parse it out to an array of arrays. Also, there are no commas in between elements.

I am receiving something similar to:

[[[a] b] c [d]]

and need to transform it to:

[[['a'], 'b'], 'c', ['d']

I've tried replacing all brackets with the bracket and a quote mark but that doesn't work. Ex: [[a] b] becomes ['['a'] b]

I've tried JSON.parse but I need help doing a couple things before that works

  1. I need to add commas in all the right places
  2. I need the values inside brackets to be wrapped in quotations.

Solution

  • Use a regular expression to put quotes around any sequence that doesn't include space or square brackets, and replace all spaces with comma. Then parse it as JSON.

    let str = '[[[a] b] c [d]]';
    let json = str.replace(/[^ \[\]]+/g, '"$&"').replace(/ +/g, ',');
    console.log(json);
    let arr = JSON.parse(json);
    console.log(arr);