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?
>Solution :
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);