变量中的 JavaScript 反斜杠 (\) 导致错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3903488/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript backslash (\) in variables is causing an error
提问by Imrul
In Javascript, when I put a backslash in some variables like:
在 Javascript 中,当我在某些变量中添加反斜杠时,例如:
var ttt = "aa ///\\";
var ttt = "aa ///\";
Javascript shows an error.
Javascript 显示错误。
If I try to restrict user in entering this character, I also get an error:
如果我尝试限制用户输入此字符,我也会收到错误消息:
(("aaa ///\\").indexOf('"') != -1)
Restricting backslashes from user input is not a good strategy, because you have to show an annoying message to the user.
限制用户输入的反斜杠不是一个好策略,因为您必须向用户显示令人讨厌的消息。
Why am I getting an error with backslash?
为什么我收到反斜杠错误?
回答by Daniel Vandersluis
The backslash (\
) is an escape characterin Javascript (along with a lot of other C-like languages). This means that when Javascript encounters a backslash, it tries to escape the following character. For instance, \n
is a newline character (rather than a backslash followed by the letter n).
反斜杠 ( \
) 是Javascript 中的转义字符(以及许多其他类似 C 的语言)。这意味着当 Javascript 遇到反斜杠时,它会尝试转义以下字符。例如,\n
是一个换行符(而不是反斜杠后跟字母 n)。
In order to output a literal backslash, you need to escape it. That means \\
will output a single backslash (and \\\\
will output two, and so on). The reason "aa ///\"
doesn't work is because the backslash escapes the "
(which will print a literal quote), and thus your string is not properly terminated. Similarly, "aa ///\\\"
won't work, because the last backslash again escapes the quote.
为了输出一个反斜杠,你需要逃脱它。这意味着\\
将输出一个反斜杠(\\\\
并将输出两个,依此类推)。原因"aa ///\"
不起作用是因为反斜杠转义了"
(将打印文字引号),因此您的字符串没有正确终止。同样,"aa ///\\\"
也不起作用,因为最后一个反斜杠再次转义了引号。
Just remember, for each backslash you want to output, you need to give Javascript two.
请记住,对于您要输出的每个反斜杠,您需要为 Javascript 提供两个.
回答by Roy Sharon
You may want to try the following, which is more or less the standard way to escape user input:
您可能想尝试以下方法,这或多或少是转义用户输入的标准方法:
function stringEscape(s) {
return s ? s.replace(/\/g,'\\').replace(/\n/g,'\n').replace(/\t/g,'\t').replace(/\v/g,'\v').replace(/'/g,"\'").replace(/"/g,'\"').replace(/[\x00-\x1F\x80-\x9F]/g,hex) : s;
function hex(c) { var v = '0'+c.charCodeAt(0).toString(16); return '\x'+v.substr(v.length-2); }
}
This replaces all backslashes with an escaped backslash, and then proceeds to escape other non-printable characters to their escaped form. It also escapes single and double quotes, so you can use the output as a string constructor even in eval (which is a bad idea by itself, considering that you are using user input). But in any case, it should do the job you want.
这将用转义的反斜杠替换所有反斜杠,然后继续将其他不可打印的字符转义为其转义形式。它还转义单引号和双引号,因此您甚至可以在 eval 中将输出用作字符串构造函数(考虑到您使用的是用户输入,这本身就是一个坏主意)。但无论如何,它应该可以完成您想要的工作。
回答by livibetter
You have to escape each \
to be \\
:
你必须逃避每个\
人\\
:
var ttt = "aa ///\\\";
Updated: I think this question is not about the escape character in string at all. The asker doesn't seem to explain the problem correctly.
更新:我认为这个问题根本与字符串中的转义字符无关。提问者似乎没有正确解释问题。
because you had to show a message to user that user can't give a name which has (\) character.
因为您必须向用户显示一条消息,该用户不能提供具有 (\) 字符的名称。
I think the scenario is like:
我认为场景是这样的:
var user_input_name = document.getElementById('the_name').value;
Then the asker wants to check if user_input_name
contains any [\
]. If so, then alert the user.
然后询问者想要检查是否user_input_name
包含任何 [ \
]。如果是,则提醒用户。
If user enters [aa ///\
] in HTML input box, then if you alert(user_input_name)
, you will see [aaa ///\
]. You don't need to escape, i.e. replace [\
] to be [\\
] in JavaScript code. When you do escaping, that is because you are trying to make of a string which contain special characters inJavaScript source code. If you don't do it, it won't be parsed correct. Since you already get a string, you don't need to pass it into an escaping function. If you do so, I am guessing you are generating another JavaScript code from a JavaScript code, but it's not the case here.
如果用户aa ///\
在 HTML 输入框中输入 [ ],那么如果您alert(user_input_name)
,您将看到 [ aaa ///\
]。您不需要转义,即在 JavaScript 代码中将\
[ \\
]替换为 [ ]。当您进行转义时,那是因为您试图在JavaScript 源代码中创建包含特殊字符的字符串。如果你不这样做,它就不会被正确解析。由于您已经获得了一个字符串,因此您无需将其传递给转义函数。如果你这样做,我猜你是从一个 JavaScript 代码生成另一个 JavaScript 代码,但这里不是这种情况。
I am guessing asker wants to simulate the input, so we can understand the problem. Unfortunately, asker doesn't understand JavaScript well. Therefore, a syntax error code being supplied to us:
我猜提问者想模拟输入,所以我们可以理解这个问题。不幸的是,asker 不太了解 JavaScript。因此,向我们提供了一个语法错误代码:
var ttt = "aa ///\";
Hence, we assume the asker having problem with escaping.
因此,我们假设提问者有逃逸问题。
If you want to simulate, you code must be valid at first place.
如果你想模拟,你的代码首先必须是有效的。
var ttt = "aa ///\"; // <- This is correct
// var ttt = "aa ///\"; // <- This is not.
alert(ttt); // You will see [aa ///\] in dialog, which is what you expect, right?
Now, you only need to do is
现在,你只需要做的是
var user_input_name = document.getElementById('the_name').value;
if (user_input_name.indexOf("\") >= 0) { // There is a [\] in the string
alert("\ is not allowed to be used!"); // User reads [\ is not allowed to be used]
do_something_else();
}
Edit: I used []
to quote text to be shown, so it would be less confused than using ""
.
编辑:我曾经[]
引用要显示的文本,所以它不会比使用""
.
回答by Talal Nabulsi
The backslash \
is reserved for use as an escape character in Javascript.
反斜杠\
保留用作 Javascript 中的转义字符。
To use a backslash literally you need to use two backslashes
要从字面上使用反斜杠,您需要使用两个反斜杠
\
回答by jknair
The jsfiddle link to where i tried out your query http://jsfiddle.net/A8Dnv/1/its working fine @Imrul as mentioned you are using C# on server side and you dont mind that either: http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.escape.aspx
jsfiddle 链接到我尝试了您的查询http://jsfiddle.net/A8Dnv/1/其工作正常@Imrul 如前所述您在服务器端使用 C# 并且您不介意:http: //msdn.microsoft .com/en-us/library/system.text.regularexpressions.regex.escape.aspx
回答by diewland
If you want to use special character in javascript variable value, Escape Character(\
) is required.
如果要在 javascript 变量值中使用特殊字符,则需要转义字符( \
)。
Backslashin your example is special character, too.
您的示例中的反斜杠也是特殊字符。
So you should do something like this,
所以你应该做这样的事情,
var ttt = "aa ///\\\"; // --> ///\\
or
或者
var ttt = "aa ///\"; // --> ///\
But Escape Characternot require for user input.
但用户输入不需要转义字符。
When you press /
in prompt box or input field then submit, that means single /
.
当您/
在提示框或输入字段中按下然后提交时,这意味着 single /
。