Home > Net >  Fast way to parse arguments from string in JavaScript
Fast way to parse arguments from string in JavaScript

Time:12-08

I want to call a function via a string such as the following:

const inputStr = "myFunc foo=bar arg2=123 arg1=baz";

so I can parse this and pass the parameters to my function myFunc({arg1:"baz", arg2: 123, foo: "bar"})

I did this several ways, mostly like this:

const params = {};
const strings = inputStr.split(" ");
strings.forEach((item)=>{
    const members = item.split("=");
    params[members[0]] = members[1];
})
myFunc(params)

I know this does not do input validation, and passes "123" instead of a number, but that could be myFunc's job, what I really need is a shorter, hopefully a one-liner way to achieve this.

Another way could be ask the user to input a valid JSON string and just do JSON.parse(input) but that is much harder to type than the original example.

Any help would be appreciated.

P.S.: For my use case, parsing only strings (maybe numbers) is enough, but maybe for a future user, a solution that also parses sub-objects could be helpful.

Thanks!

CodePudding user response:

If you are just looking to split the arguments and create an object, using Object.fromEntries() would work.

const input = "myFunc foo=bar arg2=123 arg1=baz";

let [func, ...args] = input.split(' ');
args = Object.fromEntries(args.map(arg => arg.split('=')));

console.log(args);

Automatically converting to a number/boolean type would obviously require extra effort, and if you're dealing with sub-objects, you'd first need to define the syntax that you would want to use for that in your input string. Arguably, you'd be better off using JSON in that case.

CodePudding user response:

I hope this helps:

const inputStr = "myFunc foo=bar arg2=123 arg1=baz";
const re = /(\w )=(\w )/g;
const params = {};
let match;

// Split the input string into an array of tokens
const tokens = inputStr.split(" ");

// Loop through the tokens and match the regular expression against each one
for (const token of tokens) {
  match = re.exec(token);

  // If the regular expression matched, add the key and value to the params object
  if (match) {
    params[match[1]] = match[2];
  }
}

// Call the function with the constructed params object
myFunc(params);
  • Related