javascriptjspescaping

Escape single quote with JavaScript


I am aware with escaping special characters in HTML.

But, I am still asking this as I have come across a situation.

I have a JSP, in which I am not allowed put validation on input. Users are entering special characters to test.

Input string:

'#@$%

When I am displaying from database, I am using

<%= StringEscapeUtils.escapeHtml(map[i].get("text").toString())%>

where "map" is an array of Hashmap. This works fine.

The problem comes when I need to pass this string to JavaScript using

<input type="Button"
onclick="onEdit('<%= StringEscapeUtils.escapeHtml(map[i].get("text").toString())%>',
'<%= strShortCut%>','<%= map[i].get("uid")%>')" value="Edit">

The string becomes ''#@$%'.

How do I escape a single quote?


Solution

  • If you would be using Java, maybe you can do the below in Java.

    import org.apache.commons.lang.StringEscapeUtils;
    ...
    
    String result = StringEscapeUtils.escapeJavaScript(jsString);