'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



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source