Posted:

converting javascript into a Java string

I have an HTTP server embedded in my Java application. I need to serve up a web page with some simple javascript embedded in it. Sticking the javascript in a file, and serving it that way is possible, but actually more work than I want to do for this hack. Since Java does not have support for multi-line or verbatim string literals, I need to convert the javascript into one or more Java strings.

Mostly this just involves putting the javascript inside ", but I also need to escape any existing " or \ in the javascript.

Originally, I chose to smash the javascript into a single, very long String, with all the double-quotes and backslashes escaped, and all the newlines removed, and all the comments tossed away (since // comments are terminated by a newline, if I get rid of the newlines, I need to drop the comments). That was a bit too aggressive, as the resulting javascript was impossible to debug (it shows up as one line in the web browser). Additionally, since the end-of-statement ; is optional in javascript when there is a newline by stripping the newlines, the ; are no longer optional, and so I introduced subtle bugs. (I should just look at a javascript minifier if i want to go that far ...)

For simple stringification, I ended up with this ugly mash of inefficient shell script to package up a javascript snippet as a Java string:

OUTF="$1"
STR=$(basename "$OUTF" .java)
(echo 'String '$STR' = ""'
    sed -e 's,\\,\\\\,g' | \
        sed -e 's,",\\",g' | \
        sed -e 's,\t,  ,g' | \
        sed -e 's, *$,,' | \
        sed -e 's,^\(.*\)$,    + "\1\\n",'
    echo ';'
    echo) > "$OUTF"

(This chews up its stdin, and writes it out to the first argument to the script, $1.)

For a simple javascript snippet like:

// This is a simple function
function tester (arg) {
    return "\tthis is a test " +arg+ "\n";
}

function testEscapes() {
  var eStr = "this is \"awkward\".";
  var nStr = "this\nthat\tthere";
}

Spits out:

String test2 = ""
    + "// This is a simple function\n"
    + "function tester (arg) {\n"
    + "    return \"\\tthis is a test \" +arg+ \"\\n\";\n"
    + "}\n"
    + "\n"
    + "function testCompressor() {\n"
    + "  var eStr = \"this is \\\"awkward\\\".\";\n"
    + "  var nStr = \"this\\nthat\\tthere\";\n"
    + "}\n"
    + "\n"
;

As soon as your javascript gets beyond a couple lines though, this gets out of hand pretty quick.

Comments or Questions?

Subscribe via RSS | Atom Feed