1

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.

well actually
  • 11,810
  • 19
  • 52
  • 70
  • Wouldn't [escape()](https://developer.mozilla.org/en/DOM/window.escape) work? And then use `unescape()` to convert back. – sinemetu1 Mar 15 '12 at 18:32
  • Possible dupe: [How to escape apostrophe or quotes on a JSP ( used by javascript )](http://stackoverflow.com/questions/1470768/how-to-escape-apostrophe-or-quotes-on-a-jsp-used-by-javascript) – tkone Mar 15 '12 at 18:33
  • possible duplicate of [How to escape a single quote from within a JSP?](http://stackoverflow.com/questions/9708242/how-to-escape-a-single-quote-from-within-a-jsp) – BalusC Mar 15 '12 at 19:43

3 Answers3

3

If you're using Spring, you could do this.

new SomeFunction('<spring:escapeBody javaScriptEscape="true">${foo}</spring:escapeBody>');
davidwebster48
  • 604
  • 1
  • 8
  • 21
0

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:

new SomeFunction('${myFn:escapeJs(foo)}');

See the end of this page for how to create an EL function.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
-1

you can use escapeXml in c:out

 new SomeFunction('<c:out value="${foo}" escapeXml="true"/>');
redDevil
  • 1,909
  • 17
  • 25
  • 1
    as the attribute says, `` escapes XML special characters. It doesn't escape JS special characters. – JB Nizet Mar 15 '12 at 18:56