JS输出单引号、双引号、换⾏符、回车符、退格符等特殊符号你可以在 JavaScript 中使⽤反斜杠来向⽂本字符串添加特殊字符。
插⼊特殊字符
反斜杠⽤来在⽂本字符串中插⼊省略号、换⾏符、引号和其他特殊字符。
请看下⾯的 JavaScript 代码:
var txt="We are the so-called "Vikings" from the north." document.write(txt)
在 JavaScript 中,字符串使⽤单引号或者双引号来起始或者结束。这意味着上⾯的字符串将被截为:We are the so-called。
要解决这个问题,就必须把在 "Viking" 中的引号前⾯加上反斜杠 (\)。这样就可以把每个双引号转换为字⾯上的字符串。
var txt="We are the so-called \"Vikings\" from the north." document.write(txt)
现在 JavaScript 就可以输出正确的⽂本字符串了:We are the so-called "Vikings" the north。
这是另⼀个例⼦:
document.write ("You \& me are singing!")
上⾯的例⼦会产⽣以下输出:
You & me are singing!js在字符串中添加字符
下⾯的表格列出了其余的特殊字符,这些特殊字符都可以使⽤反斜杠来添加到⽂本字符串中:
代码输出
\’ 单引号
\" 双引号
\& 和号
\\ 反斜杠
\n 换⾏符
\r 回车符
\t 制表符
\b 退格符
(⽂章来⾃,转载请保留,谢谢!)