AlgoDaily 12: Detect Substring in String

“How would you write a function to detect a substring in a string?

If the substring can be found in the string, return the index at which it starts. Otherwise, return -1.”

We can iterate through the string, and increment a counter when we hit that index in the target substring. If the counter gets to the length of the target substring, we can return the iterator index minus the counter.

If we hit a non-matching character, we reset the counter to zero. We also have to backtrack our place in the whole string by one, to avoid a false start preventing a later substring match from being off by one.

function detectSubstring(str, subStr) {
        if (str === subStr) {
                return 0;
        if (str.length < subStr.length) {
                return -1;
        let matchLength = 0;
        for (let i = 0; i < str.length; i++) {
                if (str[i] === subStr[matchLength]) {
                } else {
                        i -= 1;
                        matchLength = 0;

                if (matchLength === subStr.length) {
                        return i - (matchLength - 1);
        return -1;

This turned out to work OK, and is pretty much the solution suggested by Algo Daily.

Tech mentioned