Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

214
Views
Obtain arguments from a string seperated by a space and convert an argument in an array format to an array

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!