本文介绍了变量中的JavaScript反斜杠(\)导致错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Javascript中,当我在一些变量中添加反斜杠时:

In Javascript, when I put a backslash in some variables like:

var ttt = "aa ///\\\";
var ttt = "aa ///\"; 

Javscript显示错误。

Javscript shows an error.

如果我尝试限制用户输入此字符,我也收到错误:

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?

推荐答案

反斜杠( \ )是(以及许多其他类C语言)。这意味着当Javascript遇到反斜杠时,它会尝试逃避例如, \ n 是换行符(而不是反斜杠后跟字母n)。

The backslash (\) is an escape character in 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).

为了输出文字反斜杠,你需要转义 it 。那个mea ns \\ 将输出一个反斜杠(而 \\\\ 将输出两个,等等)。 aa /// \的原因不起作用是因为反斜杠转义了(这将打印一个文字引号),因此你的字符串没有正确终止。同样,aa /// \\\将无效,因为最后一个反斜杠再次逃脱报价。

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.

请记住,对于要输出的每个反斜杠,您需要提供Javascript 两个

Just remember, for each backslash you want to output, you need to give Javascript two.

这篇关于变量中的JavaScript反斜杠(\)导致错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 05:28