You can use backslashes in JavaScript to add special characters to text strings.
Backslashes are used to insert ellipses, newlines, quotes, and other special characters in text strings.
Please see the JavaScript code below:
var txt="We are the so-called <code>"Vikings"</code> from the north." document.write(txt)
In JavaScript, strings use single quotes or double quotes to start or end. This means that the above string will be truncated to: We are the so-called.
To solve this problem, you must add a backslash () before the quotation mark in "Viking". This converts each double quote into a literal string.
var txt="We are the so-called <code>\"Vikings\"</code> from the north." document.write(txt)
Now JavaScript can output the correct text string: We are the so-called "Vikings" from the north.
Here’s another example:
document.write ("You <code>\&</code> me are singing!")
The above example produces the following output:
You & me are singing!
The following table lists the remaining special characters that can be added to text strings using backslashes:
代码 | 输出 |
---|---|
' | 单引号 |
" | 双引号 |
& | 和号 |
\ | 反斜杠 |
n | 换行符 |
r | 回车符 |
t | 制表符 |
b | 退格符 |
f | 换页符 |