Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 335
Sarawut Positwinyu Avatar asked May 02 '11 09:05

Sarawut Positwinyu


2 Answers

\ 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 '.

like image 86
Quentin Avatar answered Oct 03 '22 18:10

Quentin


In a c# string, \ needs to be escaped, as it is a special prefix for things like \n etc. You may find it easier to use a verbatim strig literal, which doesn't need escaping (except for " to "").

For example:

@"... can\'t ..."

Note the leading @ before the string literal, which indicates the usage of the alternative escaping rules. This also allows newlines etc directly in the string, i.e.

@"foo
bar
blip"
like image 21
Marc Gravell Avatar answered Oct 03 '22 20:10

Marc Gravell