0

I have jsp code as:

onclick="showURL('${result.url}')"

${result.url} is dynamic value. When an apostrophe comes in the URL I get the error.

I have tried all the methods like escape, encodeURI, replacing the single quotes with double but nothing works.

Script call is as follows:

function showURL(name){
    alert(name);
} 
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Anshu Kunal
  • 196
  • 1
  • 13
  • possible duplicate of [Javascript escape quotes](http://stackoverflow.com/questions/2004168/javascript-escape-quotes) – JohnFx May 20 '11 at 12:58

3 Answers3

1
<%@taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
${fn:escapeXml(myString)}

See: How can I escape special HTML characters in JSP?

Community
  • 1
  • 1
George Cummins
  • 28,485
  • 8
  • 71
  • 90
1

You need to ensure that ${result.url} returns a valid URL. Quotes are invalid in URLs. It sounds like that you're returning an URL with a query string with unencoded parameters like follows

public String getUrl() {
    return "page.jsp?foo=" + foo + "&bar=" + bar;
}

You need to change the method as follows

public String getUrl() {
    return "page.jsp?foo=" + URLEncoder.encode(foo, "UTF-8") + "&bar=" + URLEncoder.encode(bar, "UTF-8");
}

You cannot fix this in the JavaScript side with escape(), etc. It's already too late then.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
0

why not just do this:

onclick=showURL("${result.url}");

function showURL (result_url) {
    alert("<c:out value='"+ result_url + "' />");
}

then you don't have to worry about escaping at all.

-tjw

Travis Webb
  • 14,688
  • 7
  • 55
  • 109
  • I have tried above but getting error a attribute name undefined in onclick call. I have used escape once and it worked for all special character except apostrophe. – Anshu Kunal May 20 '11 at 13:14
  • My code worked when i used c:out value directly in the java script body. var splCharUrl="" – Anshu Kunal May 25 '11 at 14:34