Skip to content

Instantly share code, notes, and snippets.

@yuru4c
Last active June 17, 2018 13:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yuru4c/f3466937e1789fa324d2af7ca0865887 to your computer and use it in GitHub Desktop.
Save yuru4c/f3466937e1789fa324d2af7ca0865887 to your computer and use it in GitHub Desktop.
スペース区切りのコマンド等をパース
var parse = (function () {
var rs = /\s/, rb = /\\\\/g, re = /\\(?=[\s"'])/g;
var or = {'"': /\\"/g, "'": /\\'/g};
return function parse(str) {
var args = []; var i = 0;
for (var c; c = str.charAt(i); i++) {
if (rs.test(c)) continue;
var v = ''; var b = i;
do {
if (c == '\\') { i++; continue; }
if (rs.test(c)) break;
if (c == '"' || c == "'") {
v += str.substring(b, i).replace(re, '');
b = ++i;
for (var d; d = str.charAt(i); i++) {
if (d == '\\') { i++; continue; }
if (d == c) break;
}
v += str.substring(b, i).replace(or[c], c);
b = i + 1;
}
} while (c = str.charAt(++i));
v += str.substring(b, i).replace(re, '');
args.push(v.replace(rb, '\\'));
}
return args;
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment