Skip to content

Instantly share code, notes, and snippets.

@geraldyeo
Last active August 3, 2016 04:43
Show Gist options
  • Save geraldyeo/6cf09fb2dd586f03a0c04d90caff9c69 to your computer and use it in GitHub Desktop.
Save geraldyeo/6cf09fb2dd586f03a0c04d90caff9c69 to your computer and use it in GitHub Desktop.
Write a function that takes two strings, and returns the index of the first occurrence of one string in the other.
// Write a function that takes two strings, and returns the index of the first occurrence of one string in the other
// Do not use built-in functions: indexOf, substr, substring, array.split
function indexof(strToFind, str) {
var len1 = str.length;
var len2 = strToFind.length;
var i, j, numCorrect;
for (i=0; i<len1; i++) {
numCorrect = 0;
for (j=0; j<len2; j++) {
if (str.charAt(i+j) === strToFind.charAt(j)) {
numCorrect += 1;
}
}
if (numCorrect === len2) {
return i;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment