w3pop.com :: ÍøÂçѧԺ :: JavaScript :: JS ÌØÊâ×Ö·û
In JavaScript you can add special characters to a text string by using the backslash sign.
ʹÓÃbackslash( \ ·´Ð±¸Ü)±ê¼ÇÄã¿ÉÒÔÔÚJSÖÐÌí¼ÓÌØÊâÎÄ×Ö¡£
The backslash () is used to insert apostrophes, new lines, quotes, and other special characters into a text string.
(\ ·´Ð±¸Ü)±»ÓÃÀ´²åÈëÊ¡ÂÔ·ûºÅ£¬ÐµÄÐУ¬ÒýÓÃºÍÆäËû²åÈëÔÚ×Ö·û´®ÖеÄÌØÊâÎÄ×Ö¡£
Look at the following JavaScript code:
Çë¿´ÏÂÃæµÄJS´úÂ룺
var txt="We are the so-called "Vikings" from the north." |
In JavaScript, a string is started and stopped with either single or double quotes. This means that the string above will be chopped to: We are the so-called
ÔÚJSÖУ¬Ò»×Ö·û´®¿ÉÒÔÓõ¥ÒýºÅ»òÊÇË«ÒýºÅÀ´¿ªÊ¼ºÍ½áÊø¡£Õâ¾ÍÒâζ×ÅÉÏÃæµÄ×Ö·û´®½«±»ÇгɣºWe are the so-called
To solve this problem, you must place a backslash (\) before each double quote in "Viking". This turns each double quote into a string literal:
Òª½â¾öÕâ¸öÎÊÌ⣬Äã±ØÐëÔÚ"Viking"µÄÿ¸öË«ÒýºÅǰ·ÅÖÃÒ»¸ö\ (·´Ð±¸Ü)¡£ÕâÑù¾ÍÄÜÔÚ×Ö·û´®ÖÐÕýÈ··µ»ØÃ¿¸öË«ÒýºÅÁË£º
var txt="We are the so-called "Vikings" from the north." |
JavasScript will now output the proper text string: We are the so-called "Vikings" from the north.
ÏÖÔÚJS¾ÍÄÜÊä³öºÏÊʵÄÎÄ×ÖÁË£º We are the so-called "Vikings" from the north.
Here is another example:
ÕâÊÇÁíÍâÒ»¸öÀý×Ó£º
document.write ("You & me are singing!")
|
The example above will produce the following output:
ÉÏÃæµÄÀý×Ó»áÊä³öÏÂÃæµÄÄÚÈÝ£º
You & me are singing! |
The table below lists other special characters that can be added to a text string with the backslash sign:
ÏÂÃæµÄ±í¸ñÂÞÁÐÁËÆäËûÒ»Ð©ÌØÊâÎÄ×Ö£º
| Code ´úÂë |
Outputs Êä³ö½á¹û |
|---|---|
| \' | single quote µ¥ÒýºÅ |
| \" | double quote Ë«ÒýºÅ |
| \& | ampersand &·ûºÅ |
| \\ | backslash ·´Ð±¸Ü |
| \n | new line »»Ðзû |
| \r | carriage return »Ø³µ·û |
| \t | tab ÖÆ±í·û |
| \b | backspace Í˸ñ·û |
| \f | form feed ·ÖÒ³·û |