Search code examples
javajavascriptstringescapingstringescapeutils

Java -> Apache Commons StringEscapeUtils -> escapeJavaScript


For a very simple ajax name lookup, I'm sending an id from the client webpage to the server (Tomcat 5.5, Java 5), looking it up in a database and returning a string, which is assigned to a javascript variable back in the client (and then displayed).

The javascript code that receives the value is pretty standard:

//client code - javascript
xmlHttp.onreadystatechange=function() {
    if (xmlHttp.readyState==4) {
        var result = xmlHttp.responseText;
        alert(result);
        ...
    }
    ...
}

To return the string, I originally had this in the server:

//server code - java
myString = "...";
out.write(myString.getBytes("UTF-8"));

Which worked perfectly, if unsafe. Later, I replaced it with:

import org.apache.commons.lang.StringEscapeUtils;
...
myString = "...";
out.write(StringEscapeUtils.escapeJavaScript(myString).getBytes("UTF-8"));

But while safer, the resulting string can't be properly displayed if it contains special chars like "ñ".

For instance, using:

escapeJavaScript("años").getBytes("UTF-8");

sends:

an\u00F1os

to the client.

The question: is there a simple way to parse the resulting string in Javascript or is there an alternate escape function I can use in java that would prevent this issue?


Solution

  • The following works in every browser I've tried:

    javascript:alert("a\u00F1os");
    

    Perhaps your string is being escaped twice by mistake.