-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsplit.js
More file actions
28 lines (22 loc) · 755 Bytes
/
split.js
File metadata and controls
28 lines (22 loc) · 755 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// String.prototype.split as a function
// This is the string separator version, I haven't figured out how to split string with regex
function split(str, sep) {
const res = [];
let temp = "";
for (let n = 0; n < str.length; n++) {
if (!sep.length) {
res.push(str[n]);
continue;
}
if (str.slice(n, n + sep.length) === sep) {
res.push(temp);
temp = "";
n += Math.max(sep.length - 1, 0);
} else temp += str[n];
}
if (sep.length) res.push(temp);
return res;
}
console.log(split("abc", "")); // ["a", "b", "c"]
console.log(split("abc-def-ghi", "-")); // ["abc", "def", "ghi"]
console.log(split("abc-def-ghi", "-def-")); // ["abc", "ghi"]