JavaScript 字符串
概述
??? 字符串在JavaScript中幾乎無處不在,在你處理用戶的輸入數(shù)據(jù)的時候,在讀取或設(shè)置DOM對象的屬性時,在操作cookie時,當(dāng)然還有更 多...。JavaScript的核心部分提供了一組屬性和方法用于通用的字符串操作,如分割字符串,改變字符串的大小寫,操作子字符串等。
字符串的創(chuàng)建
創(chuàng)建一個字符串有幾種方法。最簡單的是用引號將一組字符包含起來,可以將其賦值給一個字符串變量。
var myStr = "Hello, String!";
可以用雙引號或單引號將字符串包含,但要注意,作為界定字符串的一對引號必須是相同的,不能混用。
像var myString = "Fluffy is a pretty cat.'; 這樣的聲明就是非法的。
允許使用兩種引號,使得某些操作變得簡單,比如將一種嵌入另外一種:
document.write("<img src='img/logo.jpg' height='30' width='100' alt='Logo'>");
?
字符串的拼接
非常簡單,就用一個"+"將兩個字符串"相加":
var longString = "One piece " + "plus one more piece.";
要將多個字符串累積為一個字符串,還可以使用"+="操作符:
var result = "";
result += "My name is Anders"
result += " and my age is 25"; ?
?要在字符串中添加換行符,需要使用轉(zhuǎn)義字符"n":
var confirmString = "You did not enter a response to the last " +
"question.nnSubmit form anyway?";
var confirmValue = confirm(confirmString);
字符串長度
可以使用內(nèi)置屬性?length?來計算字符串的長度:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> </head> <body> <script> var txt = "Hello World!"; document.write("<p>" + txt.length + "</p>"); var txt="what are you doing ?"; document.write("<p>" + txt.length + "</p>"); </script> </body> </html>
特殊字符
在 JavaScript 中,字符串寫在單引號或雙引號來中。
因為這樣,以下實例 JavaScript 無法解析:x
?"We are the so-called "Vikings" from the north."
字符串 "We are the so-called " 被截斷。
如何解決以上的問題呢?可以使用反斜杠 () 來轉(zhuǎn)義 "Vikings" 字符串中的雙引號,如下:
?"We are the so-called "Vikings" from the north."
?反斜杠是一個轉(zhuǎn)義字符。 轉(zhuǎn)義字符將特殊字符轉(zhuǎn)換為字符串字符:
轉(zhuǎn)義字符 () 可以用于轉(zhuǎn)義撇號,換行,引號,等其他特殊字符。
下表中列舉了在字符串中可以使用轉(zhuǎn)義字符轉(zhuǎn)義的特殊字符:
代碼 ? ??輸出
' ? ?單引號 ? ?
" ? ?雙引號 ? ?
\ ? ?反斜杠 ? ?
n ? ?換行 ? ?
r ? ?回車 ? ?
t ? ?tab(制表符) ? ?
b ? ?退格符 ? ?
f ? ?換頁符
字符串可以是對象
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> </head> <body> <p id="demo"></p> <script> var x = "John"; // x是一個字符串 var y = new String("John"); // y是一個對象 document.getElementById("demo").innerHTML =typeof x + " " + typeof y; </script> </body> </html>
?注意:
不要創(chuàng)建 String 對象。它會拖慢執(zhí)行速度,并可能產(chǎn)生其他副作用 ? ?
字符串屬性和方法
原始值字符串,如 "John", 沒有屬性和方法(因為他們不是對象)。
原始值可以使用 JavaScript 的屬性和方法,因為 JavaScript 在執(zhí)行方法和屬性時可以把原始值當(dāng)作對象。