CESCO CESCO - 8 months ago 42
Javascript Question

How to parse the flag value from a LINUX command string with Javascript

I am using an http/scheduler, and the only way for me to get the specific of these tasks is reading an string that look just like this

let str = "go run tasks/action/main.go --channel=2 --state=true --username=scheduler "

let channel = ?
let state= ?


A more reliable approach would be to solve this using regular expression. As you can guarantee it to work even when state and channel option is being specified the other way around.

I am no regular expression expert , so I will be very happy if someone can recommend me a better regexr.


let str = "go run tasks/action/main.go --channel=211 --state=true --username=scheduler ";

let channel = /--channel=(.+?)\s/.exec(str)[1];
let state= /--state=(.+?)\s/.exec(str)[1];

Note that I am anchoring based on the idea that there will be a space \s behind each option.value, I think this will work in OP's use case but will not if 1 of the option.value has no space behind it. E.g. "go run blah --state=true"

Basically what I go there is to tell Regexr "Hey go look for --channel= string and capture all the characters after it until you see the next space (non-greedy)"