Posted: 5/23/2010
Hi,
How to escape single quotes in c# so that the string can be used in Javascript. Suppose in c# I am having this string "Hello this is my tes't st'ring. The single quotes are causing problems for me in javasscript when I use this string.
Posted: 5/24/2010
Hi Kevin,
//Replaces single quote (') with (\') //Here str is a String variable that contain the string value with single quote.
str = str.Replace("'", "\'");
I hope this answer will solve your problem.
Posted: 5/26/2010
This will serve you: str.Replace("'", "\\'")
Below is the sample:
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> protected void Page_Load(object sender, EventArgs e) { string str="Hello this is my tes't st'ring"; Button1.Attributes.Add("onclick", string.Format("return test('{0}')", str.Replace("'", "\\'"))); } </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> </head> <body> <form id="form1" runat="server"> <asp:Button ID="Button1" runat="server" Text="Test" /> <br /> </form> <script type="text/javascript"> function test(input) { alert(input); return false; } </script> </body> </html>