Created
July 18, 2014 17:46
-
-
Save gordonbrander/9a4a3fb880d7964e1311 to your computer and use it in GitHub Desktop.
indexesOf: collect all indexes of pattern found in 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
// Returns an array of all indexes at which `pattern` can be found in `string`. | |
function indexesOf(string, pattern) { | |
var i = -1; | |
var indexes = []; | |
// We mutate `i` in place with the result of `indexOf`. We also use the last | |
// value of `i + 1` to continue seeking from. Any index found is pushed into | |
// the `indexes` array. If we ever get `-1` as the result of `indexOf`, we | |
// stop looping. | |
while((i = string.indexOf(pattern, i + 1)) !== -1) indexes.push(i); | |
return indexes; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment