DIV CSS 佈局教程網

JavaScript 型別系統深度解析:String 字串型別
編輯:關於JavaScript     

JavaScript 沒有表示單一字元的字元型別,只有字串 String 型別——所謂字元型別,相當於僅含一個字元的字串。

String 是 JavaScript 的基本資料型別,同時語言也提供對應的 String 物件作為原始值的包裝物件。在需要時,JavaScript 會自動在原始形式與物件形式之間轉換。本文完整說明 String 原始型別與 String 包裝物件。

定義

String 型別是由引號括起、由 16 位元 Unicode 字元組成的字元序列。

字串常用於表示文字資料,此時其中每個元素都被視為一個碼點,各佔序列中的一個位置,以非負整數索引標示。首字元位於位置 0,第二個字元在位置 1,依此類推。字串長度即元素的個數(以 16 位元值計算),空字串長度為零,不含任何元素。

Unicode 編碼

所有字元都可以寫成 '\uxxxx' 的形式,xxxx 代表該字元的 Unicode 編碼。例如 \u00A9 代表版權符號:

 var s = '\u00A9'; s // "©" 

若字串含實際文字資料,每個元素都被視為一個獨立的 UTF-16 單元。每個字元在 JavaScript 內部以 16 位元(2 個位元組)的 UTF-16 格式儲存。

但 UTF-16 有兩種長度:U+0000 到 U+FFFF 之間的字元長度為 16 位元(2 個位元組);U+10000 到 U+10FFFF 之間則為 32 位元(4 個位元組),且前兩個位元組落在 0xD800 到 0xDBFF 之間,後兩個位元組落在 0xDC00 到 0xDFFF 之間。

舉例來說,U+1D306 對應的字元寫成 UTF-16 就是 0xD834 0xDF06。瀏覽器會正確將這四個位元組識別為一個字元,但 JavaScript 內部的字元長度固定為 16 位元,會把它視為兩個字元:

 var s = '\uD834\uDF06'; s // 對應 U+1D306 s.length // 2 

也就是說,對於 U+10000 到 U+10FFFF 的四位元組 Unicode 字元,JavaScript 一律視為兩個字元(length 屬性為 2)。ES6 之後可用 Array.from(s).length 或 [...s].length 取得真正的碼點數。

引號

字串以雙引號或單引號宣告。Java 用雙引號宣告字串、單引號宣告字元;由於 ECMAScript 沒有字元型別,兩種寫法都可用,但左右引號必須匹配:

 //正確 var sColor1 = "red"; var sColor2 = 'red'; //錯誤 var sColor1 = "red'; var sColor2 = 'red"; 

由單引號定界的字串中可含雙引號,反之亦然:

 'key = "value"' "It's a long journey" 

JavaScript 程式碼常夾雜 HTML 字串,HTML 屬性中也常夾雜 JavaScript。因此最好讓兩者各自維持獨立的引號風格。慣例是 JavaScript 中用單引號,HTML 事件處理器屬性中用雙引號:

 <button onclick = "alert('thanks')">click me</button> 

反斜線轉義

若要在單引號字串中使用單引號,或在雙引號字串中使用雙引號,需以反斜線(\)轉義。最常見的情況是英文縮寫與所有格的撇號——它與單引號是同一個字元,因此必須轉義:

 'Wouldn\'t you prefer this book?' //"Wouldn't you prefer this book?" 'Did she say \'Hello\'?' //"Did she say 'Hello'?" "Did she say \"Hello\"?" //"Did she say "Hello"?" 

多行字串

字串預設只能寫在一行內,硬要換行會報錯:

 //報錯 Uncaught SyntaxError: Invalid or unexpected token 'a b c'; 

在 ECMAScript 3 中,字串必須寫在一行;到了 ECMAScript 5,字串可以拆成數行,但每行必須以反斜線(\)結束。若希望在字串中真正換行,則使用轉義字元 \n:

 //"onelongline" 'one\ long\ line' /*"two lines"*/ 'two\nlines' 

轉義字元一覽

在 JavaScript 字串中,反斜線有特殊用途。反斜線後接一個字元,就不表示其字面含義,而用來表示特殊字元,稱為轉義字元:

\0 空位元組;\n 換行;\t 定位; \b 空格;\r carriage return;\f 換頁;\\ 反斜線本身;\' 單引號;\" 雙引號;\xnn 以十六進位 nn 表示一個字元(n 為 0-f),如 \x41 表示 'A';\unnnn 以十六進位 nnnn 表示一個 Unicode 字元,如 \u03a3 表示希臘字元。

如果在非特殊字元前使用反斜線,反斜線會被忽略:

'\a' // "a"

若字串本身需要包含反斜線,則要再寫一個反斜線為自己轉義:

"Prev \\ Next" // "Prev \ Next"

不可變性

JavaScript 中的字串是不可變的。一旦建立,就永遠無法改變它。要改變某個變數保存的字串,必須先銷毀原字串,再用另一個含新值的字串填入該變數。

可以透過 + 運算子串接其他字串來建立新字串:

 var lang = "java"; lang = lang + "script"; //'javascript' 

上述程式碼的實際過程是:先建立一個能容納 10 個字元的新字串,在其中填入 'java' 與 'script',最後銷毀原來的兩個字串。這個過程在背景發生,也是某些舊版瀏覽器(如 IE6)的字串拼接速度慢的原因,後續版本已改善了這個效率問題。

轉字串

把一個值轉為字串有兩種方式:toString() 與 String()。此外也可用空字串串接("" + 值)達成同樣效果。

toString():幾乎每個值都有的方法,回傳相應值的字串表示。注意 undefined 與 null 沒有這個方法:

 undefined.toString();//錯誤 null.toString();//錯誤 true.toString();//'true' false.toString();//'false' 'abc'.toString();//'abc' 1.23.toString();//'1.23' ({}).toString();//[object Object] [1,2,3,4].toString();//'1,2,3,4' (new Date()).toString();//日期字串 /ab/i.toString();//'/ab/i' 

String():在不知道值是否為 undefined 或 null 時,用這個轉型函式更安全。規則是:值為 null 回傳 'null',為 undefined 回傳 'undefined';其他值則呼叫 toString() 並回傳原始型別值;若 toString() 回傳的是物件,則改呼叫 valueOf(),若 valueOf() 仍回傳物件便報錯。

 // "3" String({toString: function () { return 3; } }) // "[object Object]" String({valueOf: function () { return 2; } }) // "3" String({ valueOf: function () { return 2; }, toString: function () { return 3; } })

length 屬性

每個 String 實例都有一個 length 屬性表示字元個數。由於字串不可變,長度也不可變。

length 不會出現在 for/in 迴圈中列舉,也不能用 delete 刪除。注意:對於字串 s,最後一個字元的索引是 s.length - 1。

 var str = "test"; console.log(str.length);//4 str.length = 6; console.log(str,str.length);//"test",4 

物件通用方法

String 型別是與字串對應的包裝型別,繼承了 Object 的三個通用方法,三者都回傳字串的原始值:

 console.log("test".valueOf());//"test" console.log("test".toString());//"test" console.log("test".toLocaleString());//"test" 

存取字元的方法

共有 charAt()、中括號索引、charCodeAt() 與 fromCharCode() 四種。

charAt() 接收一個基於 0 的位置參數,回傳該位置的字元。參數為空或 NaN 時預設為 0;超出範圍時回傳空字串:

 var str = "hello"; console.log(str.charAt(1));//e console.log(str.charAt(-1));//'' console.log(str.charAt(10));//'' console.log(str.charAt());//h console.log(str.charAt(NaN));//h

它涉及 Number() 的隱式轉換,若轉為數值則依上述規則處理,若轉為 NaN 則輸出第 0 個字元:

 var str = "hello"; console.log(str.charAt(true));//'e' console.log(str.charAt(false));//'h' console.log(str.charAt('abc'));//'h' console.log(str.charAt({}));//'h' console.log(str.charAt([2]));//'l'

注意 x.charAt(pos) 與 x.substring(pos, pos+1)、x.substr(pos,1)、x.slice(pos,pos+1) 的結果相等:

 var str = "hello"; console.log(str.charAt(1));//'e' console.log(str.substring(1,2));//'e' console.log(str.slice(1,2));//'e' console.log(str.substr(1,1));//'e' 

中括號索引:ECMAScript 5 定義了另一種存取字元的方式,用方括號加數字索引。參數超出範圍或為 NaN 時輸出 undefined;不帶參數會報錯;它沒有 Number() 的隱式轉換,但參數為單值陣列時仍可轉為數值。注意 IE7- 不支援:

 var str = "hello"; console.log(str[0]);//h console.log(str[[1]]);//e console.log(str[false]);//undefined console.log(str[-1]);//undefined console.log(str[NaN]);//undefined console.log(str[]);//報錯

charCodeAt() 類似 charAt(),但回傳指定位置的 16 位元 Unicode 編碼,範圍在 0 到 65535(0x0000-0xffff)之間。參數為空或 NaN 時預設為 0;超出範圍時回傳 NaN:

 var str = "hello"; console.log(str.charCodeAt());//104 console.log(str.charCodeAt(0));//104 console.log(str.charCodeAt(1));//101 console.log(str.charCodeAt(-1));//NaN console.log(str.charCodeAt(10));//NaN console.log(str.charCodeAt(NaN));//104

同樣涉及 Number() 的隱式轉換:

 var str = "hello"; console.log(str.charCodeAt(true));//101 console.log(str.charCodeAt(false));//104 console.log(str.charCodeAt('abc'));//104 console.log(str.charCodeAt({}));//104 console.log(str.charCodeAt([2]));//108

fromCharCode():String 建構函式本身的靜態方法,接收一個或多個字元編碼並轉為字串,可視為 charCodeAt() 的反向操作。參數為空或 NaN 時回傳空字串;超出 0-65535 範圍時輸出不可控:

 console.log(String.fromCharCode(104,101,108,108,111));//'hello' console.log(String.fromCharCode(0x6211,0x662f,0x5c0f,0x706b,0x67f4));//'我是小火柴' console.log(String.fromCharCode());//'' console.log(String.fromCharCode(NaN));//'' console.log(String.fromCharCode(-1)); console.log(String.fromCharCode(65560));

若一個字元佔用四位元組,則需拆成兩個字元表示:

 console.log(String.fromCharCode(0xD842, 0xDFB7)); // 對應 U+20BB7 

字串拼接

concat() 將一個或多個字串拼接起來並回傳新字串,原字串不變。非字串參數(第一個參數除外)會透過 String() 隱式轉換:

 var stringValue = 'hello '; var result = stringValue.concat('world','!'); console.log(result);//'hello world!' console.log(stringValue);//'hello' 

第一個參數只能是字串,其他型別(陣列除外)會報錯:

(1).concat('2');//報錯
(true).concat('false');//報錯
({}).concat('abc');//報錯

由於陣列也有 concat(),參數如何轉換取決於「先出現的是陣列還是字串」:

'1,2,3,'.concat([4,5]);//'1,2,3,4,5'
[1,2,3].concat(',4,5');//[1, 2, 3, ",4,5"]

加號運算子(+):雖然 concat() 是專用方法,實務上使用更多的是 +。它通常比 concat() 簡潔:

 var stringValue = 'hello '; console.log(stringValue.concat('world','!'));//'hello world!' console.log(stringValue + 'world' + '!');//'hello world!' 

注意:只有其中一個運算元是字串,或物件轉為字串時,才進行字串拼接:

 1 + 2;//3 '1' + 2;//'12' var o = {valueOf:function(){return '1';}}; o + 2;//'12' var o = {valueOf:function(){return 1;}}; o + 2;//3

建立子字串

slice(start, end) 回傳從 start 位置到(不含)end 位置的字元。若 end 為 undefined 或不存在,則取到字串結尾。start 為負數時 start = max(length + start, 0),end 為負數時同理。start 與 end 無法交換位置:

 var stringValue = 'hello world'; console.log(stringValue.slice());//'hello world' console.log(stringValue.slice(2));//'llo world' console.log(stringValue.slice(2,undefined));//'llo world' console.log(stringValue.slice(2,-5));//'llo ' console.log(stringValue.slice(2,-20));//'' console.log(stringValue.slice(20));//'' console.log(stringValue.slice(-2,2));//'' console.log(stringValue.slice(-2,-20));//'' console.log(stringValue.slice(-2,20));//'ld' console.log(stringValue.slice(-20,2));//'he' console.log(stringValue.slice(-20,-2));//'hello wor'

slice() 涉及 Number() 的隱式轉換:start 被轉為 NaN 時相當於 0;end 被轉為 NaN 時(undefined 除外)輸出空字串:

 var stringValue = 'hello world'; console.log(stringValue.slice(NaN));//'hello world' console.log(stringValue.slice(0,NaN));//'' console.log(stringValue.slice(true,[3]));//'el' console.log(stringValue.slice(null,undefined));//'hello world' console.log(stringValue.slice({}));//'hello world' console.log(stringValue.slice('2',[5]));//'llo'

substring(start, end) 同樣回傳 start 到(不含)end 的字元,但規則不同:任一參數為 NaN 或負數時以 0 取代;任一參數大於字串長度時以長度取代;若 start 大於 end 則交換兩者:

 var stringValue = 'hello world'; console.log(stringValue.substring());//'hello world' console.log(stringValue.substring(2));//'llo world' console.log(stringValue.substring(2,undefined));//'llo world' console.log(stringValue.substring(20));//'' console.log(stringValue.substring(-2,2));//'he' console.log(stringValue.substring(NaN,2));//'he' console.log(stringValue.substring(-2,20));//'hello world' console.log(stringValue.substring(3,2));//'l' console.log(stringValue.substring(3,NaN));//'hel' console.log(stringValue.substring(-20,2));//'he' console.log(stringValue.substring(-20,-2));//''

同樣涉及 Number() 的隱式轉換:

 var stringValue = 'hello world'; console.log(stringValue.substring(true,[3]));//'el' console.log(stringValue.substring(null,undefined));//'hello world' console.log(stringValue.substring({}));//'hello world' console.log(stringValue.substring('2',[5]));//'llo' 

substr(start, length) 的第二個參數代表要回傳的字元個數(而非結束位置)。start 為負數時 start = max(length + start, 0);start 為 NaN 時相當於 0;length 為負數或 NaN 時等於 0,因此回傳空字串。start 與 length 無法交換位置。

注意:此方法不屬於 ECMAScript 標準,已被棄用。另外 IE8- 在處理負值時有問題,會回傳原始字串:

 var stringValue = 'hello world'; console.log(stringValue.substr());//'hello world' console.log(stringValue.substr(2));//'llo world' console.log(stringValue.substr(2,undefined));//'llo world' console.log(stringValue.substr(2,NaN));//'' console.log(stringValue.substr(NaN,2));//'he' console.log(stringValue.substr(20));//'' console.log(stringValue.substr(-2,3));//'ld' console.log(stringValue.substr(-2,20));//'ld' console.log(stringValue.substr(-20,2));//'he' console.log(stringValue.substr(-20,-2));//'' console.log(stringValue.substr(2,5));//llo w

同樣涉及 Number() 的隱式轉換:

 var stringValue = 'hello world'; console.log(stringValue.substr(true,[3]));//'el' console.log(stringValue.substr(null,undefined));//'hello world' console.log(stringValue.substr({}));//'hello world' console.log(stringValue.substr('2',[5]));//'llo w' 

三者選用建議:需要「從某位置取到某位置」用 slice()(負值語意最直觀);需要「可自動交換參數順序」的寬容行為用 substring();substr() 因已棄用且跨瀏覽器行為不一致,新專案應避免使用。

字串位置查詢

indexOf(searchString, start) 回傳 searchString 首次出現的位置,找不到則回 -1。它會隱式呼叫 String() 轉換 searchString、呼叫 Number() 轉換 start(undefined 除外)。start 若被忽略或為 undefined、NaN、負數時等於 0:

 var string = 'hello world world'; console.log(string.indexOf('ld'));//9 console.log(string.indexOf('ld',undefined));//9 console.log(string.indexOf('ld',NaN));//9 console.log(string.indexOf('ld',-1));//9 console.log(string.indexOf('ld',10));//15 console.log(string.indexOf('ld',[10]));//15 console.log(string.indexOf('true',[10]));//-1 console.log(string.indexOf(false,[10]));//-1

lastIndexOf(searchString, start) 回傳最後一次出現的位置。start 若被忽略或為 undefined、NaN 時等於 length - 1。與 indexOf() 不同,若 start 為負數則回傳 -1:

 var string = 'hello world world'; console.log(string.lastIndexOf('ld'));//15 console.log(string.lastIndexOf('ld',undefined));//15 console.log(string.lastIndexOf('ld',NaN));//-1 console.log(string.lastIndexOf('ld',-1));//-1 console.log(string.lastIndexOf('ld',10));//9 console.log(string.lastIndexOf('ld',[10]));//9 console.log(string.lastIndexOf('true',[10]));//-1 console.log(string.lastIndexOf(false,[10]));//-1

要找出所有符合條件的子字串位置,可以迴圈呼叫 indexOf(),每次從「上次位置 + 子字串長度」繼續找:

 function allIndexOf(str,value){ var result = []; var pos = str.indexOf(value); while(pos > -1){ result.push(pos); pos = str.indexOf(value,pos+value.length); } return result; } console.log(allIndexOf('helllhelllhelll','ll'));//[2,7,12]

trim()

ECMAScript 5 為所有字串定義了 trim(),它建立一個副本、刪除前置與後綴的所有空白字元後回傳。由於回傳的是副本,原字串的前後空格保持不變。注意 IE8- 不支援:

 var string = ' hello world '; console.log(string.trim());//'hello world' console.log(string);//' hello world ' 

空白字元不僅是空格,還包含定位字元(\t)、換行符(\n)與 carriage return(\r):

'\r\nabc \t'.trim() // 'abc'

此外 Firefox、Safari 與 WebKit 還支援非標準的 trimRight(),用於刪除結尾空白:

 var string = ' hello world '; console.log(string.trimRight());//' hello world'; 

用 trim() 判斷輸入是否為空:

 if(usename.trim().length){ alert('correct'); }else{ alert('error'); } 

用正則表達式模擬 trim():

 function fnTrim(str){ return str.replace(/^\s+|\s+$/,'') } console.log(fnTrim(' hello world '));//'hello world'

大小寫轉換

ECMAScript 涉及大小寫轉換的方法有四個:toLowerCase()、toLocaleLowerCase()、toUpperCase()、toLocaleUpperCase()。

前兩個是經典方法,借鏡自 java.lang.String 的同名方法;後兩者則針對特定地區實作。對多數地區而言結果相同,但少數語言(如土耳其語)在 Unicode 大小寫轉換上有特殊規則,此時必須使用針對地區的方法才能正確轉換。

 var string = 'Hello World'; console.log(string.toLowerCase());//hello world console.log(string.toLocaleLowerCase());//hello world console.log(string.toUpperCase());//HELLO WORLD console.log(string.toLocaleUpperCase());//HELLO WORLD

這四種方法都不支援 String() 的隱式轉換,只接受字串型別:

(true).toLowerCase();//報錯
(2).toLocaleLowerCase();//報錯
({}).toUpperCase();//報錯
([]).toLocaleUpperCase();//報錯

它們可以連續使用:

 var string = 'Hello World'; console.log((string.toUpperCase()).toLowerCase());//hello world 

在不知道程式碼將於哪個語言環境運行的情況下,使用針對地區的方法更為穩妥。

localeCompare()

用於比較兩個字串,規則是:若字串在字母表中應排在參數之前,回傳負數(多數情況為 -1);相等回傳 0;應排在之後則回傳正數(多數為 1):

 var stringValue = 'yellow'; console.log(stringValue.localeCompare('brick'));//1 'y'> 'b' console.log(stringValue.localeCompare('yellow'));//0 'yellow' == 'yellow' console.log(stringValue.localeCompare('zoo'));//-1 'yellow' < 'zoo'

要注意:雖然在字母表中大寫字母排在小寫字母之前('B' < 'a'),但 localeCompare() 會考慮自然語言的排序慣例,把 'B' 排在 'a' 前面:

 console.log('B'.localeCompare('a'));//1 console.log('B' > 'a');//false console.log('b'.localeCompare('a'));//1 console.log('b' > 'a');//true

這正是 localeCompare() 的價值所在:它依據使用者的語言環境排序,能正確處理重音符與大小寫,而 > 運算子只是比較 UTF-16 碼點順序。實務上若要對使用者可見的清單排序,一律應使用 localeCompare(),並可傳入第二個參數指定 locale 以確保結果一致。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved