JavaScript - 反斜杠(Backslash)在字符串里的使用

1,660 阅读2分钟

Backslash As An Escape Character in String

Backslash & Forward Slash

反斜杠 Backslash: \
正斜杠 Forward Slash: /

反斜杠在字符串里面的用法

标记字符串

You can use single quotes, double quotes, or backticks to mark strings. 就是说,你可以用单引号双引号反引号来标记字符串。 具体例子:

`Down on the sea` 
"Lie on the ocean"  
'Float on the ocean' 

不管是用哪种方式标记的字符串,加入反斜杠(\)表示反斜杠后的那个字符有特殊含义,反斜杠后的字符会被包括在引号内的字符串里面。但是,三种不同的标记方式,在何时要加\字符这个问题上有一点点区别。

反斜杠使用总结

一句话总结,其实是,在引号(包括单引号、双引号、反引号)前面加不加\,取决于是否会对正确的表达造成干扰。比如,单引号会影响到单引号标记的字符串的正确表达;双引号会影响到双引号标记的字符串的正确表达;等等。
下面总结的几点,也只是部分说明上面这一句话总结的内容:

  1. 单引号或反引号标记的字符串里面,如果有双引号,两个引号前面可以不加反斜杠(\)。加上也没有问题。
  2. 双引号标记的字符串里面,如果有双引号,两个引号前面必须加反斜杠。
  3. 不论是单引号、双引号还是反引号标记的字符串里面,如果要把\n不处理成换行,都必须在\n前面加上反斜杠,写成\\n

针对结论1、2的例子

console.log('I said to my brother, "Congratulations!"'); 
console.log("I said to my brother, \"Congratulations!\""); 
console.log(`I said to my brother, "Congratulations!"`); 

上面三种情况,输出的结果都是一样的:I said to my brother, "Congratulations!" 但是你们可以看到说,在使用双引号的时候,必须在"Congratulations!"的两个引号前面都加上\。但是在单引号和反引号的情况下,可以不用加这个\

针对结论1、2、3的例子

用代码输出:A newline character is written like "\n".

const newLine1 = 'A newline character is written like "\\n".'; 
const newLine2 = "A newline character is written like \"\\n\"."; 
const newLine3 = `A newline character is written like "\\n".`; 
console.log(newLine1); 
console.log(newLine2); 
console.log(newLine3); 

具体分析:

  1. newLine1使用单引号标记字符串,所以里面的两个双引号的前面可以不加\,但\n前面必须加\
  2. newLine2使用双引号标记字符串,所以里面的两个双引号的前面都要加\,且\n前面也必须加\
  3. newLine3使用反引号标记字符串,所以里面的两个双引号的前面可以不加\,但\n前面必须加\