js 实现 String.prototype.split

358 阅读1分钟

1. 首先我们了解一下split的功能

  • 分隔符为字符串

'sdf,sdf'.split(',')  // 返回 ['sdf', 'sdf']

  • 分隔符为正则

'sdf,sdf'.split(/,/)  // 返回 ['sdf', 'sdf']

  • 第二个参数

  • 主要用于限制返回数组长度

  • 默认长度就是result 的长度,如果长度比较小,则进行截取

实现: 

String.prototype.split = function (exp, startIdx = Number.MAX_SAFE_INTEGER) {

let s = this;

const result = [];

if (exp instanceof RegExp) {

if (s.match(exp)) {

exp = s.match(exp)[0];

} else {

return [];

}

}

const expLen = exp.length;

while (true) {

if (s.indexOf(exp) === -1) {

result.push(s);

return result.splice(0, startIdx);

}

const idx = s.indexOf(exp);

result.push(s.slice(0, idx));

s = s.slice(idx + expLen);

}

};

console.log(',sdfs,,sdf,sdf,'.split(',,', 2));

console.log(',sdfs,,sdf,sdf,'.split(/,,/, 2));

console.log(',sdfs,,sdf,sdf,'.split(/,/, 3));