Skip to content

Instantly share code, notes, and snippets.

@gordonbrander
Created July 18, 2014 17:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gordonbrander/9a4a3fb880d7964e1311 to your computer and use it in GitHub Desktop.
Save gordonbrander/9a4a3fb880d7964e1311 to your computer and use it in GitHub Desktop.
indexesOf: collect all indexes of pattern found in string.
// 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