Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Return the index of all instances of an item in an String
String.prototype.indexOfAll = function(s){
// Make sure it's 1 char, use first char of string.
s = s[0];
var results = [],
result = null,
i = 0,
offset = 0, // Incremented by previous index
// Copy as to not modify.
temp = this.slice(0),
len = temp.length;
for(; i < len; i++){
result = temp.indexOf(s);
if(result > -1){
results.push(result + offset);
offset += result + 1;
// Slice at cursor position (index of last item) + 1
temp = temp.slice(result + 1);
// Reset loop to operate on new length
len = temp.length;
}
}
return results;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.