你可以在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 | 退格符 |
| /f | 換頁符 |
新聞熱點
疑難解答