Skip to content

Instantly share code, notes, and snippets.

@netpoetica
Created June 8, 2014 18:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save netpoetica/5a288a921aed2eb3d3d5 to your computer and use it in GitHub Desktop.
Save netpoetica/5a288a921aed2eb3d3d5 to your computer and use it in GitHub Desktop.
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