Matthew Bins
Matthew Bins

Reputation: 51

Splitting a string multiple ways into an array with Javascript

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();

Upvotes: 1

Views: 53

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370679

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);

Upvotes: 2

Related Questions