0

I'm trying to get an array of arguments from a string by doing the following

const str = `argument "second argument" 'third argument' \`fourth argument\``;

str.split(/\s(?=(?:[^'"`]*(['"`])[^'"`]*\1)*[^'"`]*$)/g);

The expected output:

['argument', '"second argument"', "'third argument'", '`fourth argument`']

But this comes out:

['argument', '`', '"second argument"', '`', "'third argument'", '`', '`fourth argument`']

How can I get back an array of just 4 elements?

Lord Reptilia
  • 550
  • 1
  • 4
  • 13

2 Answers2

2

After getting an array then you can use filter to filter out the unwanted string

const str = `argument "second argument" 'third argument' \`fourth argument\``;

const result = str
  .split(/\s(?=(?:[^'"`]*(['"`])[^'"`]*\1)*[^'"`]*$)/g)
  .filter((s) => /[a-z]/.test(s));

console.log(result);

You can also achieve the same result using string manipulation

const str = `argument "second argument" 'third argument' \`fourth argument\``;

const replacerFn = (match) => match.split(" ").join("_");
const result = str
  .replace(/".*?"|'.*?'|`.*?`/g, replacerFn)
  .split(" ")
  .map((s) => s.split("_").join(" "));

console.log(result);
DecPK
  • 24,537
  • 6
  • 26
  • 42
1

I suggest that you standardized your string before split to array

Replace all ` to " and so