Home > front end >  Obtain arguments from a string seperated by a space and convert an argument in an array format to an
Obtain arguments from a string seperated by a space and convert an argument in an array format to an

Time:06-29

I have arguments that will be passed by the user for a command. Each argument for a command will be seperated with a space, which will represent a new argument. Example: "arg1 arg2 arg3" converts to ["arg1", "arg2", "arg3"] where the output is a JS array. This can be done with a simple .split(" ").

However, my problem begin when trying to format an array as a command argument. My goal is to allow the user to enter an agument in the format of an array (e.g. Starts with [ may contain multiple elements seperated by a , and ends with a ]) so for example: "arg1 [elem1, elem2] arg3" converts to ["arg1", ["elem1", "elem2"], "arg3"] where the inner and outer array is a JS array.

I have tried using JSON.Parse() however, each element would require the user to have " at the start of each element which is too complex for the user and non essential to be inputting. Also, the elements may not always intend to be a string and may be Boolean, Number or a custom type.

As of currently, this has been my best solution but misses some requirements and also is non functional when an array has a space inside.

s.split(/[\[\]]|\s /).filter(arg => arg.length > 1);

I have come up with some other solutions but all are missing one thing or another in the required specification set above. A solution that can handle nested arrays would be nice however it is non-essential and could make the solution alot more complex than it needs to be.

CodePudding user response:

Let's assume no funny characters as the input. Also nesting now allowed.

var str = "arg1 [ elem1  , elem2,elem3  ]  arg3";
console.log(str)

str = str.replace(/\s*,\s*/g, ',');
str = str.replace(/\[\s*/g, '[');
str = str.replace(/\s*\]/g, ']');

var arr = str.split(/\s /);
arr = arr.map(function(elem) {
  return elem.charAt(0) == '[' ? elem.slice(1, -1).split(",") : elem;
})

console.log(arr)

  • Related