js原生实现split


原生 JavaScript 实现 split 方法
使用原生 JavaScript 实现 split 方法需要处理字符串分割逻辑,包括分隔符匹配、结果数组构建以及可选的长度限制。以下是两种实现方式:
基础实现(不考虑正则分隔符)
function customSplit(str, separator, limit) {
const result = [];
if (separator === undefined) return [str];
let startIndex = 0;
for (let i = 0; i < str.length; i++) {
if (str.substr(i, separator.length) === separator) {
result.push(str.substring(startIndex, i));
startIndex = i + separator.length;
i += separator.length - 1;
}
}
result.push(str.substring(startIndex));
return limit ? result.slice(0, limit) : result;
}
完整实现(支持正则分隔符)
function customSplit(str, separator, limit) {
const output = [];
let lastIndex = 0;
if (separator === undefined) return [str];
if (separator === '') return Array.from(str);
const regex = new RegExp(separator, 'g');
let match;
while ((match = regex.exec(str)) !== null) {
output.push(str.slice(lastIndex, match.index));
lastIndex = match.index + match[0].length;
if (limit && output.length >= limit) break;
}
output.push(str.slice(lastIndex));
return limit ? output.slice(0, limit) : output;
}
关键特性说明
- 空字符串处理:当分隔符为空字符串时,将字符串拆分为单字符数组
- undefined 处理:未提供分隔符时返回包含原字符串的数组
- 正则支持:第二个实现版本支持正则表达式作为分隔符
- limit 参数:限制返回数组的最大长度
使用示例
console.log(customSplit('a-b-c', '-')); // ['a', 'b', 'c']
console.log(customSplit('a-b-c', '-', 2)); // ['a', 'b']
console.log(customSplit('abc', '')); // ['a', 'b', 'c']
console.log(customSplit('a,b,c', /[,]/)); // ['a', 'b', 'c']
这两个实现分别展示了基础版本和完整版本的原生 split 方法实现,可根据实际需求选择使用。






