I'm trying to create a simple function that takes a string and a delimiter and then splits the string into an array based on the delimiter value. I'm trying to write this function without using the split method in javascript. So say I have a sampleInput = '123$456$789' and a delimiter = '$' then the function stringDelimiter(sampleInput, delimiter) will return ['123', '456', '789'].
var stringDelimiter = function (sampleInput, delimiter) {
var stringArray = [];
var garbageArray = [];
var j = 0;
for (var i = 0; i < sampleInput.length; i++) {
if (sampleInput.charAt(i) == delimiter) {
garbageArray = sampleInput.charAt(i);
j++;
} else {
if (!stringArray[j]) stringArray[j] = '';
stringArray[j] += sampleInput.charAt(i);
}
}
return stringArray;
}
The problem I'm having is if the delimiter appears at the beginning of the string it returns the first element of the array undefined. I'm stuck as to how I can handle this case. So if I have sampleInput = '$123$456$789' and delimiter = '$' it returns ['123', '456', '789'] and not ['undefined','123', '456', '789']. Any help would be appreciated.
split()is pretty well supported everywhere, I see few reasons you shouldn't use it.splitfunction would be to return an empty string in the first element of the result, not anundefinedvalue.indexOf()to directly find the index of the next delimiter, andsubstrto extract from the current position to there.