So I often have to generate content for webpages through servlets or jsps. In that process I sometimes run into a problem when trying to escape multiple layers of ” or ‘ when working with strings. For example I’m creating an element with a popup here:
String pvPopup = "Y'en aura pas de facile!"; out += "<img class="clickable" src="../images/question.png" onclick="alert(" + pvPopup + ");" />";
I cannot use the alternative ‘ because the text is full of them, so it breaks the sequence. I can’t escape the string inside the alert with a simple ” again because I’m already using it.
I’ve tried escaping with either triple backslash or the unicode u0022 instead, but both cause different problems and do not seem to work appropriately.
Is there a simple solution I’m missing, here? How should I go about doing this?
Advertisement
Answer
Work backwards from what you want to emit:
<img class="clickable" src="../images/question.png" onclick="alert('Y'en aura pas de facile!');">
So you want something like this:
String pvPopup = "Y'en aura pas de facile!"; out += "<img class="clickable" src="../images/question.png""; out += " onclick="alert('" + jsQuote(pvPopup) + "');">";
where jsQuote(String)
converts "Y'en aura pas de facile!"
into "Y'en aura pas de facile!"
.
(You should be able to find an existing utility method to do the JS quoting, though probably it will be in a 3rd-party library.)
Having said that, it is better to use JSPs or some other templating scheme to generate HTML, etc for an HTTP response. If you do that, then you should be looking for a JSTL tag library that can do what the (hypothetical) jsQuote
method is doing in the above.