To figure out why the method does what it does, a good strategy is to think about how it's implemented.
I don't know the native implementation of the split()
method for JS, but it occurs to me that the algorithm traverses the string looking for the passed separator, stores the left portion of the string and then continues until done.
This is a rudimentary version of a split function, with the condition that it matches a single character separator:
function split(string, separator) {
let substring = '';
const results = [];
// Iterate over the characters of the string
for (let index = 0; index < string.length; index++) {
const character = string[index];
// Check if we found the separator
if (character === separator) {
// Save the current stored substring
results.push(substring);
// Set the new substring as empty
substring = '';
} else {
// Add the character to the substring
substring += character;
}
}
results.push(substring);
return results;
}
Obviously the String.prototype.split()
method is not implemented like this, but I think it should follow the same logic (having care to consider more complex separators, such as words or regexes).
I hope this clarifies why the returned result is 2 empty strings (in your case), because:
- The
substring
starts by default as an empty string (""
)
- After finding the
separator
, the substring
(which is an empty string) is saved to the results
array and then set to an empty string again.
- Finally, after checking the whole
string
(in this case the only 1 character "/"
), the remaining substring
(also an empty string) is saved to the results
.
NOTE: split()
is not restricted to a two element array, and potentially can return an array the same length of the original string (for example, when calling it with an empty string separator).