Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

215
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda