js 实现split
实现 split 方法
在 JavaScript 中,split 方法用于将字符串分割成数组。以下是几种常见的实现方式和用法:
基本用法
const str = 'apple,banana,orange';
const arr = str.split(',');
console.log(arr); // ['apple', 'banana', 'orange']
限制分割次数
const str = 'apple,banana,orange';
const arr = str.split(',', 2);
console.log(arr); // ['apple', 'banana']
使用正则表达式分割
const str = 'apple1banana2orange';
const arr = str.split(/\d/);
console.log(arr); // ['apple', 'banana', 'orange']
处理空字符串
const str = 'apple,,banana';
const arr = str.split(',');
console.log(arr); // ['apple', '', 'banana']
自定义 split 实现
function customSplit(str, separator, limit) {
const result = [];
let current = '';
for (let i = 0; i < str.length; i++) {
if (separator === '' || str.substr(i, separator.length) === separator) {
result.push(current);
current = '';
i += separator.length - 1;
if (limit && result.length >= limit) break;
} else {
current += str[i];
}
}
if (current !== '' || !limit || result.length < limit) {
result.push(current);
}
return limit ? result.slice(0, limit) : result;
}
性能优化版本
function optimizedSplit(str, delimiter) {
const result = [];
let start = 0;
let index = str.indexOf(delimiter);
while (index >= 0) {
result.push(str.substring(start, index));
start = index + delimiter.length;
index = str.indexOf(delimiter, start);
}
result.push(str.substring(start));
return result;
}
处理特殊字符
const str = 'apple.banana.orange';
const arr = str.split('.');
console.log(arr); // ['apple', 'banana', 'orange']
多分隔符处理

const str = 'apple,banana;orange|grape';
const arr = str.split(/[,;|]/);
console.log(arr); // ['apple', 'banana', 'orange', 'grape']
这些实现涵盖了 split 方法的主要功能和使用场景,可以根据具体需求选择合适的实现方式。






