Sarawut Positwinyu Sarawut Positwinyu - 3 months ago 10
ASP.NET (C#) Question

why using javascript escape character of quotation in string need to be \\' instead of \'

I just having a problems with javascript i am using on code behind on asp.net, after a few hour of figuring it out it turn out to be the problem of escape character.

At first i use this.

ScriptManager.RegisterStartupScript(this, this.GetType(), "temp", "alert('Can't delete this data because it is bound with rate plan');", true);


This will made javascript error because quotation at "can't" need to use escape character so i use.

ScriptManager.RegisterStartupScript(this, this.GetType(), "temp", "alert('Can\'t delete this data because it is bound with rate plan');", true);


but it still not work.

at last i use

ScriptManager.RegisterStartupScript(this, this.GetType(), "temp", "alert('Can\\'t delete this data because it is bound with rate plan');", true);


and it is fine.

i am just curious why we need to use
\\'
instead of
\'
in order to make escape character works correctly.

Answer

\ is an escape character in C# and in JavaScript.

When you give C# "\'" is creates a string containing an apostrophe.

When you give C# "\\'" then the first \ escapes the second \ (so the second \ isn't treated as an escape character) and the ' is treated as a plain ' (because the string is not delimited with '.