views:

64

answers:

2

I am retrieving a value from our DB using JSTL. I am inserting it right into some javascript to use it as a variable. I need the output of the value the JSTL is holding to be escaped because if there are single or double quotes it breaks my script. The value is user specified.

Example:

Doing the following:

<c:set var="myVar" value="Dale's Truck"/>

<script type="text/javascript">
    var mayVar = '${myVar}';
</script>

Would actually end up looking like:

<script type="text/javascript">
    var mayVar = 'Dale's Truck';//extra single quote breaks the JS
</script>

So I need to convert the JSTL var to be escaped like "Dale%27s Truck" before is gets to the JS because its already too late when it gets to my JS to be able to do it in JS.

+3  A: 

Try using fn:replace:

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

<c:set var="myVar" value="Dale's Truck" />
<c:set var="search" value="'" />
<c:set var="replace" value="%27" />

<c:set var="myVar" value="${fn:replace(myVar, search, replace)}"/>

or you can escape the single quote with a backslash:

<c:set var="replace" value="\\'" />

or if you don't even want to do all that and you are sure that the string won't contain double quotes, why not do:

var myVar = "${myVar}"; //string enclosed with double quotes instead of single quotes

But if the string has double quotes, you will still need to escape them:

<c:set var="search" value="\"" />
<c:set var="replace" value="\\\"" />
Vivin Paliath
That works, thanks! I used the double backslash approach instead of %27.
Dale
A: 

You need to use the <c:out> tag for escaping. See here and here. Without it, if myVar contains data that is user supplied and is meant to be displayed somewhere on the screen in HTML your application will be vulnerable to cross-site scripting. If it isn't user supplied and you are sure that there will not be any angle brackets or double quotes, or if the value isn't going to be displayed in HTML anywhere, then the solution in Vivin Paliath's answer will be enough.

laz
This produces HTML entities like `'` for `'`. Not really suitable in JS code.
BalusC
Doesn't that depend on what the intended usage of the string is? If it is going to be displayed in a div or something, it will work correctly right?
laz