Skip to content

Instantly share code, notes, and snippets.

@tejzpr
Created February 5, 2018 21:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tejzpr/c53b05169718e7cea294dc75206470aa to your computer and use it in GitHub Desktop.
Save tejzpr/c53b05169718e7cea294dc75206470aa to your computer and use it in GitHub Desktop.
Javascript strstr
String.prototype.strstr = function(needle) {
const haystack = this;
if(!needle) return [0];
if(!haystack || needle.length > haystack.length) return [-1];
let i,j;
let positions = [];
for(i=0;i<haystack.length;i++) {
let index = i;
j=0;
while(haystack[index] == needle[j]) {
if(j == needle.length-1) {
positions.push(i);
}
index++;j++;
}
}
return positions.length>0?positions:[-1];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment