为什么在字符串中使用引号的javascript转义字符需要'而不是'
本文关键字:转义字符 javascript 字符串 为什么 | 更新日期: 2023-09-27 17:54:03
我只是有一个javascript的问题,我在asp.net上使用的代码,经过几个小时的计算,它原来是转义字符的问题。
一开始我用这个。
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);
和它是好的。
我只是好奇为什么我们需要使用'''
而不是''
,以使转义字符正确工作
'
是c#中的转义字符和JavaScript中的。
当你给出c# "''"
时,它创建一个包含撇号的字符串。
当您给c# "'''"
时,则第一个'
转义第二个'
(因此第二个'
不被视为转义字符),'
被视为普通'
(因为字符串没有用'
分隔)。
在c#字符串中,'
需要转义,因为它是'n
等东西的特殊前缀。您可能会发现使用逐字字符串更容易,它不需要转义(除了"
到""
)。例如:
@"... can''t ..."
注意字符串字面值之前的前导@
,它指示了替代转义规则的使用。这也允许在字符串中直接使用换行符等,即
@"foo
bar
blip"
因为"'"也是c#的转义字符。
我更喜欢在字符串开始之前使用@特殊操作符,因为它告诉c#它不能处理转义字符。
例如:ScriptManager.RegisterStartupScript(this, this.GetType(), "temp", @"alert('Can''t delete this data because it is bound with rate plan');", true);
无论如何,我找不到一个quot的意义。您可以使用双quot字符串表示法来避免转义这个单quot:
ScriptManager.RegisterStartupScript(this, this.GetType(), "temp", "alert('"Can't delete this data because it is bound with rate plan'");", true);
如果我不记得有很多PHP程序员贡献脚本,我就不理解JavaScript中滥用单引号,因为这种语言的行为方式不同,取决于单引号或双引号字符串。
无论如何,你可以检查另一个关于JavaScript中单引号和双引号的问题:
- 在JavaScript中何时使用双引号或单引号?
当你使用''时,它会在实际的javascript中转义为'。你实际上转义了两次
名称中的单引号和撇号(比如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