Output JSTL escaped?

15,698

Solution 1

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="\\\"" />

Solution 2

The other answer was already accepted, but David Balazic made a great point. The <spring:escapeBody> function works best.

<spring:escapeBody htmlEscape="false" javaScriptEscape="true">${myVar}</spring:escapeBody>

Share:
15,698
Mechlar
Author by

Mechlar

I am a senior software developer and team/project manager. I develop with Javascript, Angular, React, NodeJS, Firebase, jQuery, CSS, Bootstrap, HTML5, etc, etc.

Updated on July 19, 2022

Comments

  • Mechlar
    Mechlar almost 2 years

    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.

  • Mechlar
    Mechlar almost 14 years
    That works, thanks! I used the double backslash approach instead of %27.
  • David Balažic
    David Balažic over 8 years
    Never ever write your own escaping function! Because it WILL be wrong. For example the double backslash example fails for the input "a b \\'c". It will be converted to \\' so the backslash gets escaped and the single quote will end the string. Use existing functions that are proven and debugged, e.g. var x = '<spring:escapeBody htmlEscape="false" javaScriptEscape="true">${myVar}</spring:escapeBody>';