Last active
August 29, 2015 14:22
-
-
Save jbsouvestre/b1e12ce7e018ca0418cb to your computer and use it in GitHub Desktop.
Args parser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for that. I'm trying to get the same behavior as node.js argument parser for process.argv, and it seems to print