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"']
And I want to put them back together:
['"Hello there, my friend!"', '"1 2 3"']
But I can have multiple strings, and store each one of these full strings in an array, let's call it fullStrings
.
CodePudding user response:
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);
CodePudding user response:
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; }