我正试图通过执行以下从字符串中获取一个参数数组
const str = `argument "second argument" 'third argument' `fourth argument``;
str.split(/s(?=(?:[^'"`]*(['"`])[^'"`]*1)*[^'"`]*$)/g);
预期输出:
['argument', '"second argument"', "'third argument'", '`fourth argument`']
但结果是:
['argument', '`', '"second argument"', '`', "'third argument'", '`', '`fourth argument`']
如何取回一个只有4个元素的数组?
获取数组后,可以使用filter
过滤掉不需要的字符串
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);
使用字符串操作也可以获得相同的结果
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);
我建议您在拆分为数组之前对字符串进行标准化
将所有`替换为">因此