well actually
well actually

Reputation: 12370

Escaping characters when passing jsp var to js function

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.

Upvotes: 1

Views: 3771

Answers (3)

davidwebster48
davidwebster48

Reputation: 580

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

new SomeFunction('<spring:escapeBody javaScriptEscape="true">${foo}</spring:escapeBody>');

Upvotes: 3

redDevil
redDevil

Reputation: 1919

you can use escapeXml in c:out

 new SomeFunction('<c:out value="${foo}" escapeXml="true"/>');

Upvotes: -1

JB Nizet
JB Nizet

Reputation: 691685

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.

Upvotes: 0

Related Questions