5

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.

Marcel Korpel
  • 21,536
  • 6
  • 60
  • 80
Sarawut Positwinyu
  • 4,974
  • 15
  • 54
  • 80

5 Answers5

7

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

Marcel Korpel
  • 21,536
  • 6
  • 60
  • 80
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
3

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"
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
3

Because "\" is the escaping character for C# too.

I'd prefer to use @ special operator at the beggining of your string, just before it starts it, because it tells C# that it mustn't process escaping characters.

For example:

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

Anyway, I don't find the point of a single quot. You can avoid escaping this single quot by using double-quot string notation:

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

I don't understand the abuse of single quot in JavaScript if I don't remember there're a lot of PHP coders contributing scripts, since this language behaves in a different way depending of single or double-quoted strings.

Anyway, you can check this other question about single and double-quoting in JavaScript:

Community
  • 1
  • 1
Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
  • Thank you, I don't have much idea about single quote and double quote, thank you for point out this issue so i can use it more properly next time :) – Sarawut Positwinyu May 02 '11 at 10:07
  • Absolutely, I find a bad approach using "advantages" of other languages in JavaScript or any other one if these are useless :) Great to know it was useful. – Matías Fidemraizer May 02 '11 at 10:11
1

When you use \\ it escapes to \ in the actual javascript which escapes the character. You are essentially escaping twice

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
Matt
  • 7,100
  • 3
  • 28
  • 58
0

Single quotes and apostrophes in names (such as O'Brian) are usually causing trouble in dynamic client scripts, because they'll break them and allow to insert malicious code (aka scripting attacks).

I have written the following C#6 extension method for code-behind to solve this:

public static class Extension
{
    public static string ToSQEscapedStringJS<T>(this T unescapedStr)
    {
        if (unescapedStr == null || unescapedStr.ToString() == "")
        {
            return "''";
        }
        // replace ' by @@@
        var escapedStr = (unescapedStr).ToString().Replace("'", "@@@"); 
        // JS code to replace @@@ by '
        string unEscapeSQuote = "replace(/@{3}/g, String.fromCharCode(0x27))"; 
        // add @@@ escaped string with conversion back to '
        return $"('{escapedStr}'.{unEscapeSQuote})"; 
    }
}

Its usage is simple. Consider the following dynamic script example:

// contains apostroph (aka single quote) and is dangerous for your script block
var name = "O'Brian"; 
var nameEscp = name.ToSQEscapedStringJS(); // creates JS expression from it
// building up the script
string strScript = 
   $"<script>window.opener.document.forms(0).{control.Value}.value = {nameEscp};</script>";
ClientScript.RegisterClientScriptBlock(this.GetType(), "anything", strScript);

Note that nameEscp is already surrounded by single quote so you can safely place it after the =.

The trick is that the string is escaped and upon assignment immediately unescaped (by executing a JavaScript expression) on the fly, i.e.

.value = ('O@@@Brian'.replace(/@{3}/g, String.fromCharCode(0x27));

will be the inserted assignment expression which will be sent to the client as script. After execution, .value contains O'Brian.

Matt
  • 25,467
  • 18
  • 120
  • 187