Split string từ vị trí tùy ý (không phải index 0)
String.prototype.split() luôn bắt đầu từ đầu chuỗi. Để split từ index n, cần kỹ thuật: split toàn bộ, rồi loại bỏ n phần tử đầu.
Giải pháp: Helper function
const splitFromIndex = (str, startIndex, separator = ' ') => {
// 1. Split toàn bộ
const allParts = str.split(separator);
// 2. Lấy phần từ startIndex trở đi
return allParts.slice(startIndex);
};
// Hoặc cách gốc trong bài (phức tạp hơn, giữ lại để tham khảo)
const returnSplittedArray = (str, startPosition, separator = ' ') => {
const leftOver = str.split(separator, startPosition);
const actual = str.split(separator);
leftOver.forEach(left => {
actual.splice(actual.indexOf(left), 1);
});
return actual;
};
Ví dụ sử dụng
const string = 'The quick brown fox jumped over the wall';
// Split từ index 5 (bỏ 5 từ đầu)
console.log(splitFromIndex(string, 5, ' '));
// [ "over", "the", "wall" ]
// So sánh
console.log(string.split(' '));
// [ "The", "quick", "brown", "fox", "jumped", "over", "the", "wall" ]
// ↑ index 5
Mở rộng: Split với giới hạn (limit) - split() có sẵn
// split(separator, limit) - GIỚI HẠN SỐ PHẦN TỬ TRẢ VỀ (từ đầu)
const str = 'a,b,c,d,e';
str.split(','); // ["a", "b", "c", "d", "e"]
str.split(',', 3); // ["a", "b", "c"] - chỉ 3 phần tử đầu
str.split(',', 0); // []
Các trường hợp nâng cao
1. Split từ index với regex
function splitFromIndexRegex(str, startIndex, regex) {
const matches = [...str.matchAll(regex)];
return matches.slice(startIndex).map(m => m[0]);
}
2. Split string thành chunks kích thước cố định
function chunkString(str, size) {
return str.match(new RegExp(`.{1,${size}}`, 'g')) || [];
}
chunkString('abcdefgh', 3); // ["abc", "def", "gh"]
3. Split nhưng giữ delimiter
function splitKeepDelimiter(str, regex) {
// Sử dụng lookahead/lookbehind
return str.split(new RegExp(`(?=${regex.source})`));
}
// Hoặc dùng matchAll với capturing groups
function splitWithDelimiter(str, regex) {
const parts = [];
let lastIndex = 0;
for (const match of str.matchAll(regex)) {
parts.push(str.slice(lastIndex, match.index));
parts.push(match[0]);
lastIndex = match.index + match[0].length;
}
parts.push(str.slice(lastIndex));
return parts.filter(Boolean);
}
Lưu ý hiệu suất
split()tạo mảng mới - tốn bộ nhớ với chuỗi rất lớn.- Cách
slice(startIndex)sau khi split toàn bộ đơn giản và nhanh. - Cách
splicetrong bài gốc O(n²) doindexOflặp lại - không khuyến nghị.