https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/
Solution 1
/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
var strStr = function (haystack, needle) {
if (haystack.length === 0) {
if (needle.length === 0) return 0;
return -1;
}
if (haystack.length !== 0) {
if (needle.length === 0) return 0;
}
let index;
const needleFirstStr = needle[0];
for (let i = 0; i < haystack.length; i++) {
if (haystack[i] === needleFirstStr) {
if (haystack.substring(i, i + needle.length) === needle) {
index = i;
break;
} else {
index = -1;
}
} else {
index = -1;
}
}
return index;
};