Split string by space, but ignore space after some words and space in quotes

Viewed 191

I need help splitting a string in javascript by space, tab and comma, and ignoring space after "LLC" and "S-Corps" words and space inside quotes expression.

I have string:

const line = 'LLC "Company Name" S-Corps Company-1, LLC "Company-2" Company-3 S-Corps "Company-4"';

I need to get this:

["LLC "Company Name"", "S-Corps Company-1", "LLC "Company-2"", "Company-3", "S-Corps "Company-4""]

this is my code:

const words = line.split(/(?<!LLC|S-Corps)[\s,]/);

and I get this:

["LLC "Company", "Name"", "S-Corps Company-1", "", "LLC "Company-2"", "Company-3", "S-Corps "Company-4""]

how can I fix it?

1 Answers

One option could be to assert not LLC or S-Corps to the left, and assert pairs of double quotes to the right.

To prevent empty entries after the split, you can repeat the character class [\s,]+ 1 or more times.

(?<!LLC|S-Corps)[\s,]+(?=(?:[^"]*"[^"]*")*[^"]*$)

The pattern matches:

  • (?<!LLC|S-Corps) Negative lookbehind, assert not LLC or S-Corps directly to the left
  • [\s,]+ Match 1+ occurrences of a whitespace char or ,
  • (?=(?:[^"]*"[^"]*")*[^"]*$) Positive lookahead to assert pairs of " till the end of the string.

Regex demo

const line = 'LLC "Company Name" S-Corps Company-1, LLC "Company-2" Company-3 S-Corps "Company-4"';
const regex = /(?<!LLC|S-Corps)[\s,]+(?=(?:[^"]*"[^"]*")*[^"]*$)/g;
console.log(line.split(regex));

Related