javascript in the shell

Different languages are good for different things. But unix shell style trumps all. An example:

bin/urlencode

#!/usr/bin/js
 
function urlEncode(str){
    str=escape(str);
    str=str.replace(new RegExp('\\+','g'),'%2B');
    return str.replace(new RegExp('%20','g'),'+');
}
 
 
if(arguments && arguments.length > 0) {
    for(var i = 0; i < arguments.length; i++) {
        r = urlEncode(arguments[i]);
        print(r);
    }
} else {
    importPackage(java.io);
    importPackage(java.lang);
    S = new BufferedReader( new InputStreamReader(System['in']) );
    s = true;
 
    while (s){
        s = S.readLine();
        if (s) {
            r = urlEncode(s);
            print(r);
        }
    }
}

Notes:

  • This works because /usr/bin/js on my system runs Rhino

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*