1

I want to split a string that has "" and spaces.


My input would be:

'!command "string one" so "string two" st "string three" st'

And the array should be:

array[0] = "string one"
array[1] = "so"
array[2] = "string two"
array[3] = "st" // ect....

Right now this my code, which takes the command and then the arguments behind it:

const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
2
  • share an example of the expected result Commented Nov 23, 2019 at 2:31
  • Has absolutely nothing to do with node or discord Commented Nov 23, 2019 at 6:20

1 Answer 1

2

Use a regular expression and .match either non- " characters, or match non-spaces (of which the first character isn't a "):

const input = '"string one" so "string two" st "string three" st';
const output = input.match(/\b[^"]+\b|(?!")\S+/g);
console.log(output);

Or, to be a bit more robust, match the "s too and then .map:

const input = '"string one" so "string two" st "string three" st';
const output = input
  .match(/"[^"]+"|\S+/g)
  .map(str => str.startsWith('"') ? str.slice(1, str.length - 1) : str);
console.log(output);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.