-1

The title of the question is a bit wonky but can be better explained with an example. I am attempting to make a custom command-line for user input. I take in the user's input as a string but I would like to parse the commands arguments into an array. I am able to use .split(" ") to split up the string at all the spaces but would like to keep anything between quotes, square brackets, and curly brackets as one argument (brackets keep them inside of argument). Example:

let input = "command arg 1 \"arg 2\" [arg 3] {arg 4}";

let arguments = input.parseArgs(); // Returns a list of: ["arg", "1", "arg 2", "[arg 3]", "{arg 4}"]

I have attempted to use regex to search through the command but I feel that there is an easier way.

Summary, take all arguments of a command and place them into an array but include strings as one argument and brackets as a full argument.

  • _"attempted to use regex"_... did it not work? That's how I'd approach this. You should include your attempts in your question so others can help you with any problems – Phil Feb 21 '22 at 03:12
  • FYI this is basically the same as CSV parsing. Perhaps this answers your question? [How can I parse a CSV string with JavaScript, which contains comma in data?](https://stackoverflow.com/q/8493195/283366). Though having multiple arg _containers_ makes this extra complex – Phil Feb 21 '22 at 03:14
  • You're on the right track with split and mapping over regex replace. I think the regex will look something like `/[\[\]\{\}\"]+/g` – danh Feb 21 '22 at 03:17

1 Answers1

0

Most of the chars you're looking to match are special chars in regex, so you'll need a lot of escapes (preceding \s).

let input = "command arg 1 \"arg 2\" [arg 3] {arg 4}";
let comps = input.split(" ").slice(1);
let noquotes = comps.map(c => c.replace(/[\[\]\{\}\"]+/g, ""));
console.log(noquotes)
danh
  • 62,181
  • 10
  • 95
  • 136