0

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("'","&#39;");

And also

 nameString = nameString.replaceAll("'","&apos;");

I still cannot get it to work. And also I can't go for EL.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nur Aini
  • 393
  • 2
  • 5
  • 14

4 Answers4

1

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

Community
  • 1
  • 1
Martin Wilson
  • 3,386
  • 1
  • 24
  • 29
1

Try to use String.fromCharCode(39) instead of single quote, String.fromCharCode(39) is ASCII codes for single quote.

0

The following worked for me, as the HTML encoding is done before the function call and replaced the single quote with &#39;.

nameString = nameString.replaceAll("&#39;","\\'");
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0

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.