String.prototype.split() 是字符串分割為數組的核心方法。它支援字符串或正則表達式作為分隔符,可選限制返回數組長度。本文系統講解語法、正則分隔符進階用法、常見陷阱、性能優化與實戰場景。
str.split(separator, limit)
// separator: 分隔符
// - 字符串:精確匹配
// - 正則表達式:模式匹配(含捕獲組行為差異)
// - 空字符串 '':按字符分割(UTF-16 代碼單元)
// - 未提供/undefined:返回 [原字符串]
// limit: 可選,非負整數,限制返回數組最大長度
// - 超出部分被丟棄
// - 為 0 返回空數組
var str = 'Hello World!';
// 字符串分隔符
str.split(' '); // ["Hello", "World!"]
str.split(''); // ["H","e","l","l","o"," ","W","o","r","l","d","!"] (按字符)
str.split('o'); // ["Hell", " W", "rld!"]
// 限制長度
str.split(' ', 1); // ["Hello"] (只取第一個)
str.split(' ', 2); // ["Hello", "World!"]
// 正則分隔符
'1,2;3|4'.split(/[,;|]/); // ["1", "2", "3", "4"]
'a1b2c3d'.split(/\d/); // ["a", "b", "c", "d"]
' a b '.split(/\s+/); // ["", "a", "b", ""] (首尾空白產生空字符串)
關鍵差異:分隔符正則包含捕獲組時,匹配到的捕獲組內容會被插入結果數組中。
'a1b2c3d'.split(/(\d)/); // ["a", "1", "b", "2", "c", "3", "d"] - 數字被保留
'a1b2c3d'.split(/\d/); // ["a", "b", "c", "d"] - 數字被丟棄
// 實戰:保留分隔符
'key=value;name=test'.split(/([=;])/);
// ["key", "=", "value", ";", "name", "=", "test"]
',a,b,'.split(','); // ["", "a", "b", ""]
// 解決:過濾空字符串
',a,b,'.split(',').filter(Boolean); // ["a", "b"]
var regex = /\d/g;
'1a2b3c'.split(regex); // ["", "a", "b", "c"]
regex.lastIndex; // 6 - 正則對象狀態被改變!
// 避免:每次 new RegExp 或不使用 g 標誌
'1a2b3c'.split(/\d/); // 安全
'👨👩👧👦'.split('');
// ["👨", "", "👩", "", "👧", "", "👦"] - 破壞組合字符
// 正確:展開運算符按 Unicode 字符分割
[...'👨👩👧👦']; // ["👨👩👧👦"] (單個 Grapheme Cluster)
| 場景 | 優化建議 |
|---|---|
| 固定字符串分隔符 | 用字符串而非正則:str.split(',') 比 str.split(/,/) 快 2-3 倍 |
| 大字符串分割 | 考慮 String.prototype.matchAll 或手寫索引查找避免創建大量中間數組 |
| 重複使用正則 | 預編譯 const regex = /,/,避免字面量重複創建 |
| 只需前 N 段 | 使用 limit 參數:str.split(',', 3) 避免全部分割 |
function parseQuery(queryString) {
return queryString.split('&').reduce((params, pair) => {
var [key, value] = pair.split('=');
params[decodeURIComponent(key)] = decodeURIComponent(value || '');
return params;
}, {});
}
// 'a=1&b=2&c=3' -> {a:'1', b:'2', c:'3'}
function parseCSVLine(line) {
// 處理引號包裹、逗號轉義
return line.split(/,(?=(?:[^"]*"[^"]*")*[^"]*$)/);
// 正則:只分割不在雙引號內的逗號
}
var path = '/api/users/123/profile';
var segments = path.split('/').filter(Boolean); // ["api", "users", "123", "profile"]
var arr = ['a', 'b', 'c'];
arr.join('-'); // "a-b-c"
arr.join(''); // "abc"
arr.join(', '); // "a, b, c"
// split/join 互為逆操作
var str = 'a,b,c';
str.split(',').join(';'); // "a;b;c"
split() 核心掌握:字符串分隔符最快、正則捕獲組會插入結果、limit 限制長度、Unicode 用展開運算符。實戰中結合 filter(Boolean) 去空、reduce 構建對象、join 逆向拼接。大數據分割考慮流式處理或 Web Worker 避免阻塞主線程。