JavaScript backslash (\) in variables is causing an error

前端 未结 6 2042
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 15:19

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

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

Javascript shows an erro

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 16:11

    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).

    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.

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

提交回复
热议问题