为什么在字符串中使用JavaScript转义字符需要是\\'而不是 \'

发布于 2024-11-04 11:37:53 字数 771 浏览 0 评论 0原文

我只是在 asp.net 上的代码后面使用 javascript 时遇到问题,经过几个小时的弄清楚,原来是转义字符的问题。

一开始我用这个。

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

这会导致javascript错误,因为“can't”处的引号需要使用转义字符,所以我使用。

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

但它仍然不起作用。

最后我用了

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

,效果很好。

我只是好奇为什么我们需要使用 \\' 而不是 \' 以使转义字符正常工作。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

金橙橙 2024-11-11 11:37:53

\ 是 C# 中的转义字符 和 JavaScript 中的

当您给 C# "\'" 时,会创建一个包含撇号的字符串。

当您给出 C# "\\'" 时,第一个 \ 会转义第二个 \ (因此第二个 \不被视为转义字符),并且 ' 被视为普通 ' (因为该字符串不是用 ' 分隔的。

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

忆伤 2024-11-11 11:37:53

在 ac# 字符串中,\ 需要转义,因为它是 \n 等内容的特殊前缀。您可能会发现逐字使用更容易strig 文字,不需要转义(""" 除外)。

例如:

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

注意前导 @ 字符串文字之前,表示替代转义规则的使用,这也允许直接在字符串中使用换行符等,即。

@"foo
bar
blip"

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"
物价感观 2024-11-11 11:37:53

因为“\”也是 C# 的转义字符。

我更喜欢在字符串的开头(就在字符串开始之前)使用 @ 特殊运算符,因为它告诉 C# 它不能处理转义字符。

例如:

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

无论如何,我找不到单引号的意义。您可以通过使用双引号字符串表示法来避免转义这个单引号:

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

如果我不记得有很多 PHP 编码人员贡献了脚本,我就不明白 JavaScript 中单引号的滥用,因为这种语言的行为方式是根据单引号或双引号字符串的不同方式。

无论如何,您可以检查有关 JavaScript 中单引号和双引号的其他问题:

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:

浅忆流年 2024-11-11 11:37:53

当您使用 \\ 时,它会在实际的 javascript 中转义为 \ ,从而转义该字符。你本质上是在逃避两次

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

无言温柔 2024-11-11 11:37:53

名称中的单引号和撇号(例如 O'Brian)通常会在动态客户端脚本中引起麻烦,因为它们会破坏它们并允许插入恶意代码(也称为脚本攻击)。

我为代码隐藏编写了以下C#6扩展方法来解决这个问题:

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})"; 
    }
}

它的用法很简单。请考虑以下动态脚本示例:

// 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);

注意nameEscp 已被单引号括起来,因此您可以安全地将其放在 = 之后。

诀窍在于,字符串会被转义,并且在赋值时立即立即转义(通过执行 JavaScript 表达式),即,

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

将作为插入的赋值表达式将作为脚本发送到客户端。执行后,.value 包含 O'Brian

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文