JavaScript 中的字串為原始型別,但透過 String 包裝物件提供豐富的實例方法。所有方法**不會修改原字串**,而是回傳新字串或相關資訊。
| 類別 | 方法 | 說明 | 回傳值 |
|---|---|---|---|
| 查找與定位 | indexOf(searchValue, fromIndex) | 從前往後找第一個匹配位置 | 索引號 或 -1 |
lastIndexOf(searchValue, fromIndex) | 從後往前找第一個匹配位置 | 索引號 或 -1 | |
search(regexp) | 正則表達式搜尋 | 索引號 或 -1 | |
| 擷取與切割 | slice(start, end) | 擷取片段 (支援負索引) | 新字串 |
substring(start, end) | 擷取片段 (不支援負索引,自動調換順序) | 新字串 | |
substr(start, length) | 已棄用,擷取指定長度 | 新字串 | |
split(separator, limit) | 分割成陣列 | 字串陣列 | |
| 大小轉換 | toLowerCase() | 轉小寫 | 新字串 |
toUpperCase() | 轉大寫 | 新字串 | |
toLocaleLowerCase() | 依地區設定轉小寫 | 新字串 | |
toLocaleUpperCase() | 依地區設定轉大寫 | 新字串 | |
| 替換與修剪 | replace(searchValue, replaceValue) | 替換第一個匹配 (支援正則與函式) | 新字串 |
replaceAll(searchValue, replaceValue) | 替換所有匹配 (ES2021) | 新字串 | |
trim() | 移除首尾空白 | 新字串 | |
trimStart()/trimLeft() | 移除開頭空白 | 新字串 | |
trimEnd()/trimRight() | 移除結尾空白 | 新字串 | |
| 檢測與比較 | startsWith(str, pos) | 是否以指定字串開頭 | Boolean |
endsWith(str, len) | 是否以指定字串結尾 | Boolean | |
includes(str, pos) | 是否包含指定字串 | Boolean | |
localeCompare(str) | 依地區排序規則比較 | 數值 (-1,0,1) | |
| 字元存取 | charAt(index) | 回傳指定位置單一字元 | 字串 |
charCodeAt(index) | 回傳 UTF-16 編碼單元 | Number | |
codePointAt(index) | 回傳 Unicode 碼點 (支援補充平面) | Number | |
| 其他 | repeat(count) | 重複字串 N 次 | 新字串 |
padStart/End(targetLength, padString) | 頭/尾補齊字串 | 新字串 |
slice vs substring vs substrconst str = "JavaScript";
str.slice(0, 4); // "Java"
str.slice(-6); // "Script" (負索引從尾部算起)
str.substring(0, 4); // "Java"
str.substring(4, 0); // "Java" (自動調換)
// str.substr(0, 4); // "Java" - 已棄用,勿使用
建議:統一使用 slice(),行為一致且支援負索引。
replace 配合函式"file_01.txt".replace(/_(\d+)/, (_, num) => `_${String(Number(num)+1).padStart(2, '0')}`);
// "file_02.txt"
const url = "https://example.com/path";
url.startsWith("https://"); // true
url.endsWith(".com"); // false
url.includes("example"); // true
// 實用:路由守衛
function isExternalLink(href) {
return href.startsWith("http") && !href.startsWith(location.origin);
}
padStart 補零const fmt = (n) => String(n).padStart(2, '0');
const now = new Date();
`${now.getFullYear()}-${fmt(now.getMonth()+1)}-${fmt(now.getDate())} ${fmt(now.getHours())}:${fmt(now.getMinutes())}`;
// "2024-01-15 09:05"
const emoji = "👨👩👧👦"; // 家庭表情符號 (ZWJ 序列)
emoji.length; // 11 (UTF-16 碼元數)
[...emoji].length; // 1 (視覺字素簇)
emoji.codePointAt(0); // 128104 (0x1F468 - 男人)
emoji.charCodeAt(0); // 55357 (高代理項)
處理 Emoji 或罕見字時,請使用 for...of、Array.from()、codePointAt(),避免 charCodeAt/split('') 造成字元破碎。
join('') 或 StringBuilder 模式,避免 + 產生大量中間字串。const regex = /pattern/g;。includes() 比 indexOf() !== -1 更具語意。熟練掌握 slice、replace/replaceAll、trim、startsWith/endsWith/includes、padStart/End 等現代方法,能讓字串處理程式碼更具可讀性、正確性與效能。請避免使用已棄用的 substr,並注意 Unicode 字元的正確處理方式。