如何实现接收分隔符并返回分割函数的JavaScript split()?
实现柯里化的split函数
你需要实现的是一个柯里化的split函数,核心逻辑是外层函数保存分隔符,内层函数处理字符串的分割逻辑。下面分两种场景给出实现方案:
场景1:仅支持单字符分隔符
如果你的分隔符是单个字符,可以用简单的遍历实现:
const split = (separator) => { return (str) => { if (str === '') return []; const result = []; let currentSegment = ''; // 遍历字符串的每个字符 for (const char of str) { if (char === separator) { // 遇到分隔符,将当前累积的片段加入结果 result.push(currentSegment); currentSegment = ''; } else { // 非分隔符,继续累积片段 currentSegment += char; } } // 加入最后一段未被分割的内容 result.push(currentSegment); return result; }; };
测试示例
const splitByComma = split(','); console.log(splitByComma('a,b,c')); // 输出: ["a", "b", "c"] console.log(splitByComma('a,,b')); // 输出: ["a", "", "b"] console.log(splitByComma('')); // 输出: [] console.log(splitByComma('hello')); // 输出: ["hello"]
场景2:支持多字符分隔符
如果需要处理类似--、||这类多字符分隔符,需要修改遍历逻辑,检查连续的子串是否匹配分隔符:
const split = (separator) => { return (str) => { if (str === '') return []; const result = []; let currentSegment = ''; const sepLength = separator.length; for (let i = 0; i < str.length; i++) { // 检查当前位置开始的子串是否匹配分隔符 if (i + sepLength <= str.length && str.slice(i, i + sepLength) === separator) { result.push(currentSegment); currentSegment = ''; // 跳过分隔符的长度,避免重复遍历 i += sepLength - 1; } else { currentSegment += str[i]; } } // 加入最后一段内容 result.push(currentSegment); return result; }; };
测试示例
const splitByDoubleDash = split('--'); console.log(splitByDoubleDash('a--b--c')); // 输出: ["a", "b", "c"] console.log(splitByDoubleDash('a----b')); // 输出: ["a", "", "b"] console.log(splitByDoubleDash('hello--world')); // 输出: ["hello", "world"]
补充说明
如果需要完全模拟原生String.prototype.split的所有特性(比如正则分隔符、分割次数限制),可以直接在内层函数中调用原生方法:
const split = (separator) => { return (str, limit) => { return str.split(separator, limit); }; };
这个版本最简洁,且兼容所有原生split的功能,但如果是需要手动实现分割逻辑,前面的两个版本更符合需求。
内容的提问来源于stack exchange,提问作者trainee
相关产品推荐
相关产品推荐

