Escaping ' in Javascript ?

  • Thread starter Thread starter Ben
  • Start date Start date
B

Ben

I tried to pass in a query string to a open window via
the following codes :

string strName = tbName.Text.Trim();

Response.Write("<SCRIPT> javascript:window.open
('Search.aspx?Name=" + strName
+ "', 'Search', 'width=600,height=550,left=280,top=100,scr
ollbars=1,resizable=1,status=1') </SCRIPT>");

It works fine if the var value is for eg. John. However
when the var value contains the ' char, it hits into
error.

How do you escape the ' char in this case?

Thanks,
Ben
 
You can escape the apostophe by using double backlashes (in C#). One
backslash is to escape the apostrophe in C#, and the second is to escape it
in JavaScript.

If you're using VB.NET, you only need one backslash.

C#: strName = strName.Replace("'", "\\'");
VB.NET: strName = strName.Replace("'", "\'")

Hope this helps,

Mun
 
-----Original Message-----
You can escape the apostophe by using double backlashes (in C#). One
backslash is to escape the apostrophe in C#, and the second is to escape it
in JavaScript.

If you're using VB.NET, you only need one backslash.

C#: strName = strName.Replace("'", "\\'");
VB.NET: strName = strName.Replace("'", "\'")

Hope this helps,

Mun







.
 
Ben said:
I tried to pass in a query string to a open window via
the following codes :

string strName = tbName.Text.Trim();

Response.Write("<SCRIPT> javascript:window.open
('Search.aspx?Name=" + strName
+ "', 'Search', 'width=600,height=550,left=280,top=100,scr
ollbars=1,resizable=1,status=1') </SCRIPT>");

It works fine if the var value is for eg. John. However
when the var value contains the ' char, it hits into
error.

How do you escape the ' char in this case?

See this posting:


http://groups.google.com/[email protected]

for a routine that will escape most everything properly.
 
Back
Top