2022-12-16 02:06:14 +00:00
|
|
|
/**
|
|
|
|
* Takes a string and splits it into an array by whitespace, ignoring any
|
|
|
|
* text that is wrapped in quotes. You must escape quotes within a quoted
|
|
|
|
* string, otherwise it will just split on those.
|
|
|
|
*
|
|
|
|
* Derived from https://stackoverflow.com/a/46946420
|
|
|
|
*/
|
|
|
|
export default (str: string): string[] => {
|
|
|
|
let quoted = false;
|
2023-01-12 19:31:47 +00:00
|
|
|
const parts = [''] as string[];
|
2022-12-16 02:06:14 +00:00
|
|
|
|
2023-01-12 19:31:47 +00:00
|
|
|
for (const char of str.trim().match(/\\?.|^$/g) || []) {
|
2022-12-16 02:06:14 +00:00
|
|
|
if (char === '"') {
|
|
|
|
quoted = !quoted;
|
|
|
|
} else if (!quoted && char === ' ') {
|
|
|
|
parts.push('');
|
|
|
|
} else {
|
|
|
|
parts[Math.max(parts.length - 1, 0)] += char.replace(/\\(.)/, '$1');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (parts.length === 1 && parts[0] === '') {
|
|
|
|
return [];
|
|
|
|
}
|
|
|
|
|
|
|
|
return parts;
|
|
|
|
};
|