Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

199
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda