My argument parser works by taking every word in your string and splitting it by the spaces. I want to put the arguments back together, but only if it is between "'s, like this
My argument list would look like this:
['"Hello', 'there,', 'my', 'friend!"', '"1', '2', '3"', 'gold']
And I want to put them back together:
['"Hello there, my friend!"', '"1 2 3"', 'gold']
But I can have multiple strings, and store each one of these full strings in an array, let's call it fullStrings.
I also want to make it so one-worded, no-quote arguments will also be included.
Kind of simple solution in declarative way
Using: Array#join String#replaceAll String#split
const result = ['"Hello', 'there', ',', 'my', 'friend!"', '"1', '2', '3"']
.join(' ') // '"Hello there , my friend!" "1 2 3"'
.replaceAll(' ,', ',') // '"Hello there, my friend!" "1 2 3"'
.replaceAll('" "', '"" ""') // '"Hello there, my friend!"" ""1 2 3"'
.split('" "'); //['"Hello there, my friend!"', '"1 2 3"']
result.map((o) => console.log(o));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
After many, many hours of head scratching I came up with this abombination of a regex:
function parseArgs(input) {
return Array.from(input.matchAll(/"((?:[^"]|"\S*")*)"(?=\s)|(?<=^|\s)([^"\s]+)(?=$|\s)/g)).map(a => a[2] ?? a[1]);
}
console.log(parseArgs(`"Hello there, my friend!" "1 2 3" gold`))
You could try something like this but it does include a space after the there i.e. there , which may not be suitable for you?
output = ['"Hello there , my friend!"', '"1 2 3"']
const words = ['"Hello', 'there', ',', 'my', 'friend!"', '"1', '2', '3"']
let fullString = '';
words.forEach((word, index) => {
fullString += (index > 0)? ` ${word}`:`${word}`; //create sentence
});
// split on '"' and filter out empty values
const fullStrings = fullString.split('"').filter(Boolean).map((r)=>{
let result = (r != ' ')? `"${r}"`: null;
return result;
}).filter(Boolean); //remove null
console.log(fullStrings);