Really, pretty much what the title says.
Say you have this string:
var theString = \"a=b=c=d\";
Now, when you run theString
The answer from Asad is excellent as it allows for variable length RegExp separators (e.g. /\s+/g
, splitting along any length of whitespace, including newlines). However, there are a couple issues with it.
exec
can return null
and cause it to break. This can happen if the separator does not appear in the input string.The following addresses these two issues:
export function split(input, separator, limit) {
if (!separator.global) {
throw new Error("The split function requires the separator to be global.");
}
const output = [];
while (limit--) {
const lastIndex = separator.lastIndex;
const search = separator.exec(input);
if (search) {
output.push(input.slice(lastIndex, search.index));
}
}
output.push(input.slice(separator.lastIndex));
return output;
}