Say I have some jsp var foo
<c:set var="foo" value="foo's bar"/>
And I have the following js
<script>
new SomeFunction('${foo}');
</script>
This will clearly produce the error
missing ) after argument list
Because the statement ends up being
new SomeFunction('foo's bar');
However, I don’t want to just surround the argument ${foo} with double quotes, because foo’s value could also have one double quote in its string, which would cause the same problem. Assume that foo could be any string at all. I only set it to foo’s bar so the example would be clear. Currently, I’m solving the problem like so:
<script>
new SomeFunction('<c:out value="${foo}"/>');
</script>
and within SomeFunction:
SomeFunction = new function(foo) {
$(someSelector).text($("<div/>").html(foo).text());
}
This solution seems to work – assuming I’m not missing some corner cases. However, I’m not convinced this is the best solution. Any alternatives or suggestions for improvement? It seems sort of hacky to me to use that temporary div and I’d prefer a solution where it is not needed.
Implement a static method using Apache commons-lang
StringEscapeUtils.escapeEcmaScript()(or reimplement it yourself) to escape the special characters (single and double quotes, newlines, tabs), then make this function an EL function, and use this EL function from inside the JSP:See the end of this page for how to create an EL function.