字串是 JavaScript 中最常用的資料型別之一。String 對象提供了豐富的屬性與方法,支援長度檢測、字元存取、搜尋、替換、切割、大小寫轉換、比較等操作。
回傳指定索引位置的字元(長度為 1 的字串)。索引超出範圍回傳空字串。
'abc'.charAt(0); // 'a'
'abc'.charAt(5); // ''
注意:對非 BMP 字元(如 Emoji)支援有限,建議改用 codePointAt()。
回傳指定位置字元的 UTF-16 編碼(0~65535)。索引無效回傳 NaN。
'a'.charCodeAt(0); // 97
'😀'.charCodeAt(0); // 55357 (高代理項)
完整 Unicode 編碼需配合 codePointAt() 或同時檢視 charCodeAt(i) 與 charCodeAt(i+1)。
連接多個字串並回傳新字串,原字串不變。效能較差,強烈建議使用 + 運算子或模板字面量。
從前往後搜尋子字串首次出現位置,找不到回傳 -1。區分大小寫。
var str = "Hello world world!";
str.indexOf("wo"); // 6
str.indexOf("wo", 10); // 12
從後往前搜尋子字串最後出現位置,參數用法同 indexOf。
str.lastIndexOf("wo"); // 12
str.lastIndexOf("wo", 6); // 6
依據地區排序規則比較兩字串,回傳負數/0/正數。支援 locales 與 options 參數(現代瀏覽器)。
'ä'.localeCompare('z', 'de'); // -1 (德語: ä 排在 z 前)
'ä'.localeCompare('z', 'sv'); // 1 (瑞典語: ä 排在 z 後)
依正則表達式匹配字串。行為取決於 g 旗標:
g:回傳類陣列物件,含 index、input 屬性,相當於 regexp.exec(str)。g:回傳所有匹配子字串陣列,無額外屬性。'Hello world!'.match('world'); // ["world", index: 6, input: "Hello world!"]
'1 plus 2 equal 3'.match(/\d+/g); // ["1", "2", "3"]
替換匹配內容,回傳新字串。replacement 可為字串(含 $ 特殊變數)或函式。
'abc'.replace('b', 'X'); // "aXc"
'abc'.replace(/b/, (m) => m + m); // "abbc"
'2024-01-01'.replace(/(\d{4})-(\d{2})/, '$2/$1'); // "01/2024"
| 方法 | 用途 |
|---|---|
| slice(start, end) | 擷取子字串(支援負索引) |
| substring(start, end) | 擷取子字串(不支援負索引) |
| substr(start, length) | 已棄用,擷取指定長度子字串 |
| toUpperCase() / toLowerCase() | 大小寫轉換 |
| trim() / trimStart() / trimEnd() | 移除首尾空白 |
| split(separator, limit) | 分割為陣列 |
| startsWith() / endsWith() / includes() | ES6 新增,檢查開頭/結尾/包含 |
| repeat(count) | 重複字串 |
| padStart() / padEnd() | 補齊長度 |
'text')而非 new String() 物件。join('') 或模板字面量,避免 + 產生中間物件。g 旗標,否則僅匹配第一次。codePointAt()、String.fromCodePoint()、[...str] 展開運算子。