Skip to content

Instantly share code, notes, and snippets.

@jbsouvestre
Last active August 29, 2015 14:22
Show Gist options
  • Select an option

  • Save jbsouvestre/b1e12ce7e018ca0418cb to your computer and use it in GitHub Desktop.

Select an option

Save jbsouvestre/b1e12ce7e018ca0418cb to your computer and use it in GitHub Desktop.
Args parser
// the magic
var re = new RegExp(/([^\s"']+)|"([^"]*)"|'([^']*)'/);
/**
* parse a command line argument and returns sit as a splitted array
* @param {String} input
**/
function parseArgs(input){
var args = input.split(re);
var parsed = [];
for(let i = 0; i < args.length; i++){
if(args[i] != null && args[i].trim('')){
parsed.push(args[i]);
}
}
return parsed;
}
// example
var str = 'test --a "test a" -a -v key1=value1 key2="value with spaces" key3=\'with single quotes\'';
console.log(parseArgs(str));
// ["test", "--a", "test a", "-a", "-v", "key1=value1", "key2=", "value with spaces", "key3=", "with single quotes"]
@oNaiPs
Copy link

oNaiPs commented Jun 3, 2015

Thanks for that. I'm trying to get the same behavior as node.js argument parser for process.argv, and it seems to print

node a.js test --a "test a" -a -v key1=value1 key2="value with spaces" key3='with single quotes'
[ 'node',
  '/Users/onaips/a.js',
  'test',
  '--a',
  'test a',
  '-a',
  '-v',
  'key1=value1',
  'key2=value with spaces',
  'key3=with single quotes' ]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment