你可以在 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" from the north。
這是另一個例子:
document.write ("You \& me are singing!")
上面的例子會產生以下輸出:
You & me are singing!
下面的表格列出了其余的特殊字符,這些特殊字符都可以使用反斜杠來添加到文本字符串中:
代碼 輸出
\’ 單引號
\" 雙引號
\& 和號
\\ 反斜杠
\n 換行符
\r 回車符
\t 制表符
\b 退格符
(文章來自哈哈網,轉載請保留,謝謝!)