How to escape apostrophe or quotes on a JSP (used

2019-01-02 20:55发布

I have a user form. If the user types in a string with ' or " as part of it I have no problem. The form is submitted and saved correctly to the database. My problem is when I reload the page (all entries can be modified and are loaded into a list in the JSP before being displayed). On loading the page I get an error saying:

missing ) after argument list 'Caroline's message', \n

What do I need to do to escape this string for displaying it on the frontend?

Here is the code I am using on the frontend to read in the data and store it in a JavaScript object. I am not fully sure where I need to escape. The field causing the problem is c.getComName:

communications[<%=i%>][1] = new CommObject('<%=c.getComId()%>', '<%=c.getComName()%>');

UPDATED WITH HTML GENERATED:

communications[0][1] = new CommObject('101', 'Caroline's Message');

8条回答
与君花间醉酒
2楼-- · 2019-01-02 21:40

You could use JSP core tags:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>      
var jsVar = "<c:out value='${stringVariable}' />";
查看更多
十年一品温如言
3楼-- · 2019-01-02 21:42

That's strange.

What about:

'<%=c.getComName().replaceAll("\\'","\\\\'")%>'

If that works, you just have to figure out how to add the \".

查看更多
登录 后发表回答