Nur Aini
Nur Aini

Reputation: 393

Single quote JSP to JavaScript function

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.

Upvotes: 0

Views: 3574

Answers (4)

Dilip Kumar
Dilip Kumar

Reputation: 1

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;","\\'");

Upvotes: 0

Stephen M -on strike-
Stephen M -on strike-

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

user1306004
user1306004

Reputation:

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

Upvotes: 1

Martin Wilson
Martin Wilson

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

Related Questions