Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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