Loading ...

How to escape single quotes in c# so that the string can be used in Javascript

Who is online?  0 guests and 0 members
home  »  forums   »  asp.net topics   »  client side web development   » How to escape single quotes in c# so that the string can be used in Javascript

How to escape single quotes in c# so that the string can be used in Javascript

Posts under the topic: How to escape single quotes in c# so that the string can be used in Javascript

Posted: 5/23/2010

Lurker 235  points  Lurker
  • Joined on: 10/16/2009
  • Posts: 47

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.

 


tags c#, javascript

Posted: 5/24/2010

Lurker 52  points  Lurker
  • Joined on: 5/24/2010
  • Posts: 10

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

Guru 16518  points  Guru
  • Joined on: 4/19/2009
  • Posts: 483
  Answered

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>



tags c#, escape
Page 1 of 1 (3 items)