How to split a string based on two conditions using a regular expression?

  • 0
    I need to split a string by space or comma. This is how I do it: string.split (/ (?:, | \ S) + /) How to prevent a string from splitting at space if it is in a substring which is inside the square brackets? For example:
    Line: f, [, s, q,], [abc def] jkl mno
    Result:
    ["f", "[", "s", "q", "]", "[abc def]", "jkl", "mno"]
    JavaScript Anonymous, Sep 7, 2019

  • 1 Answers
  • 0
    While I came up with this

    const string = 'f, [, s, q, ], [abc def] jkl mno';
    const matches = string.match(/(\[[\w\s]+\])|([^\s,]+)/g);

    console.log(matches); // [ 'f', '[', 's', 'q', ']', '[abc def]', 'jkl', 'mno' ]
    Elijah Rogers

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!