Created
June 8, 2014 18:52
-
-
Save netpoetica/5a288a921aed2eb3d3d5 to your computer and use it in GitHub Desktop.
Return the index of all instances of an item in an String
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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