js原生实现split
原生 JavaScript 实现 split 方法
split 是 JavaScript 字符串的原生方法,用于将字符串按指定分隔符拆分为数组。以下是手动实现 split 功能的几种方法:
方法一:基础实现(按字符拆分)
function customSplit(str, delimiter) {
const result = [];
let current = '';
for (let i = 0; i < str.length; i++) {
if (str[i] === delimiter) {
result.push(current);
current = '';
} else {
current += str[i];
}
}
result.push(current); // 添加最后一部分
return result;
}
// 示例
console.log(customSplit('a,b,c', ',')); // 输出: ['a', 'b', 'c']
说明:
- 遍历字符串,遇到分隔符时将当前累积的子串加入结果数组。
- 最后需处理剩余的子串。
方法二:支持多字符分隔符
function customSplit(str, delimiter) {
const result = [];
let start = 0;
let index = str.indexOf(delimiter);
while (index !== -1) {
result.push(str.slice(start, index));
start = index + delimiter.length;
index = str.indexOf(delimiter, start);
}
result.push(str.slice(start)); // 添加剩余部分
return result;
}
// 示例
console.log(customSplit('hello##world##!', '##')); // 输出: ['hello', 'world', '!']
说明:
- 使用
indexOf查找分隔符位置,通过slice截取子串。 - 支持多字符分隔符(如
##)。
方法三:支持正则表达式分隔符
function customSplit(str, delimiter) {
const result = [];
let lastIndex = 0;
const regex = new RegExp(delimiter, 'g');
let match;
while ((match = regex.exec(str)) !== null) {
result.push(str.slice(lastIndex, match.index));
lastIndex = match.index + match[0].length;
}
result.push(str.slice(lastIndex)); // 添加剩余部分
return result;
}
// 示例
console.log(customSplit('a1b2c', /\d/)); // 输出: ['a', 'b', 'c']
说明:
- 通过正则表达式匹配分隔符,处理动态模式(如数字、空格等)。
方法四:处理空字符串和限制拆分次数
function customSplit(str, delimiter, limit) {
const result = [];
let start = 0;
let index = str.indexOf(delimiter);
while (index !== -1 && result.length < limit - 1) {
result.push(str.slice(start, index));
start = index + delimiter.length;
index = str.indexOf(delimiter, start);
}
result.push(str.slice(start)); // 添加剩余部分
return result;
}
// 示例
console.log(customSplit('a,b,c,d', ',', 2)); // 输出: ['a', 'b,c,d']
说明:
- 通过
limit参数控制拆分后的数组长度。 - 当达到限制时,剩余部分作为最后一个元素。
注意事项
- 原生
split的边界情况:- 空分隔符:将字符串拆分为单字符数组。
- 分隔符在开头/结尾:生成空字符串元素。
- 性能优化:
- 对于长字符串,避免频繁拼接(如方法一),优先使用
slice(如方法二)。
- 对于长字符串,避免频繁拼接(如方法一),优先使用
- 正则表达式:
- 复杂分隔符(如多个空格)需通过正则实现,但需注意贪婪匹配问题。
以上方法可根据实际需求组合或扩展,覆盖原生 split 的核心功能。







