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

198
Vistas
Extract optional arguments / parameters from a string

Lets say I have the following string, which I may receive and require my program to act up on:

ACTION -F filter string -L location string -M message string

How can I reliably extract the 'arguments' from this string, all of which are optional to the user?

I spent a lot of time instead writing ACTION, filter, location, message and using .split(", ") to put the args to an array but found this too difficult to work reliably.

var content = req.body.Body.split(", ");    // [ Type, Filter, Location, Message]
var msgType = content[0].trim().toUpperCase();
            
if (msgType === 'INFO') {
    // return info based on remainder of parameters
    var filterGroup = content[1].trim();
    var destination = content[2].trim();

    var message = '';
                    
    // The message may be split further if it is written
    // with a ',' so concat them back together.
    if (content.length > 2) { // Optional message exists
                        
        // Message may be written in content[3] > content[n]
        // depending how many ', ' were written in the message.
        for (var i = 3; i < content.length; i++) {
                            
            message += content[i] + ", ";
                            
        }
    }

}

Is the -a argument format even the best way? Much googling returns information on extracting the arguments used to run a nodeJS program, but that isn't applicable here, as the program is already running and the string not used at runtime. I'm at the design stage so have complete control over the format of the user input, but they're sending a SMS with these commands so the simpler the better!

I'm writing in javascript and would appreciate your thoughts

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can use a regex to match the -X pattern and then use a loop to extract the strings between each pattern match.

The regex here is /(?<=\s)\-[A-Za-z](?=\s)/g, which looks for a dash followed by a letter with a white space character on either side.

const input = "ACTION -F filter string -L location string -M message string";
let regex = /(?<=\s)\-[A-Za-z](?=\s)/g;

let args = [];
while(match = regex.exec(input))
{
  args.push(match);
}

let solved = [];
for(let i = 0; i < args.length; i++)
{
  let cmd = args[i][0];
  let idx = args[i].index;
  let val;
  if(i + 1 == args.length)
    val = input.substr(idx + cmd.length + 1);
  else
    val = input.substring(idx + cmd.length + 1, args[i + 1].index - 1);
  solved.push({
    cmd: cmd,
    val: val
  });
}

console.log(solved);

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