Reputation: 393
I have a string that must be used to be passed into a JavaScript function. I have tried many ways, but I still cannot make it to work.
<a href="javascript:goFac('<%=name%>')"><%=name%></a>
The name field is a string that contains single quotes such as It's Morning. I have tried to use:
String nameString = rs.getString("name");
nameString = nameString.replaceAll("'","\'");
<a href="javascript:goFac('<%=nameString %>')"><%=nameString%></a>
And also
nameString = URLEncoder.encode(nameString);
And also
nameString = nameString.replaceAll("'","'");
And also
nameString = nameString.replaceAll("'","'");
I still cannot get it to work. And also I can't go for EL.
Upvotes: 0
Views: 3574
Reputation: 1
The following worked for me, as the HTML encoding is done before the function call and replaced the single quote with '
.
nameString = nameString.replaceAll("'","\\'");
Upvotes: 0
Reputation: 1077
If you are doing it inside JSP tag, you need to have sufficient backslashes for one of them to actually make it into the web page. The code would be:
<a href="javascript:goFac('<%=nameString.replaceAll("'", "\\\\'") %>')"><%=nameString%></a>
You need one backslash to escape the other backslash and each of those needs to be escaped - hence four backslashes (yuck).
Hope that helps.
Upvotes: 0
Reputation:
Try to use String.fromCharCode(39) instead of single quote, String.fromCharCode(39) is ASCII codes for single quote.
Upvotes: 1
Reputation: 3386
If you want to replace a single quote (') in a String with a JavaScript-escaped (backslashed) single quote (\') in Java code then you need to escape the backslash character (with a backslash!). For example:
nameString = nameString.replaceAll("'","\\'");
See also: String.replaceAll single backslashes with double backslashes
Upvotes: 1