Skip to content

Instantly share code, notes, and snippets.

@wayerr
Last active March 30, 2017 15:27
Show Gist options
  • Save wayerr/d3c0c9ddf93d876246ba0b4eed1ec974 to your computer and use it in GitHub Desktop.
Save wayerr/d3c0c9ddf93d876246ba0b4eed1ec974 to your computer and use it in GitHub Desktop.
javascript code for parse unix-style cmd line
<html>
<style>
body, html {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
.container {
margin: auto;
width: 70%;
}
textarea {
width: 100%;
display: block;
}
</style>
<body>
<div class="container">
<textarea id=cmdsrc>
ping -i "quoted 'string'" --with and\ some\ with\ escaped\ spaces
</textarea>
<button onclick="cmddst.value = JSON.stringify(cmd.parse(cmdsrc.value))">-&gt;</button>
<button onclick="cmdsrc.value = cmd.join(JSON.parse(cmddst.value))">&lt;-</button>
<textarea id=cmddst>
</textarea>
</div>
<script>
var cmd = new (function() {
const escapes = new Set(['\\', ' ', '\'', '\"']);
this.parse = function(str) {
var args = [];
var arg = '';
function push() {
var tr = arg.trim();
if(tr.length == 0) {
return;
}
args.push(tr);
arg = '';
}
var quote = null;
var escape = false;
for(var i=0; i < str.length; i++) {
var ch = str.charAt(i);
if(!escape && ch === '\\') {
let nexti = i + 1;
if(nexti < str.length && escapes.has(str.charAt(nexti))) {
escape = true;
continue;
}
}
if(escape) {
escape = false;
} else {
if(quote) {
if(ch === quote) {
quote = null;
push();
continue;
}
} else if(ch === ' ') {
push();
continue;
} else if(ch === '\"' || ch === '\'') {
quote = ch;
continue;
}
}
arg += ch;
}
push();
return args;
};
this.join = function(args) {
var str = '';
function append(arg) {
for(var i = 0; i < arg.length; ++i) {
var ch = arg.charAt(i);
if(escapes.has(ch)) {
str += '\\';
}
str += ch;
}
}
for(var arg of args) {
if(str.length !== 0) {
str += ' ';
}
append(arg);
}
return str;
}
})();
var cmdsrc = document.getElementById('cmdsrc');
var cmddst = document.getElementById('cmddst');
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment