Find the position of the first occurrence of a substring in a string - JavaScript

Question

Find the position of the first occurrence of a substring in a string. Returns -1 if the substring is not found.

Origin from: Glassdoor


Solution 1:

str.indexOf(substring);

"Blue Whale".indexOf("Blue");     // returns  0
"Blue Whale".indexOf("Blute");    // returns -1

Solution 2:

function stringPosition(needle, haystack) {

    var m = needle.length,
        n = haystack.length;


    if (!m || !n || m > n) {
        return -1;
    }

    if (m === n) {
        return needle === haystack ? 0 : -1;
    }

    for (var j = 0; j < n; j++) {

        for (var i = 0; i < m; i++) {

            if (needle[i] !== haystack[i + j]) {
                break;
            }

            if (i === m - 1) {
                return j;
            }

        }

    }

    return -1;
}

console.log(stringPosition('Blue', 'Blue Whale'));     // returns  0
console.log(stringPosition('Blute', 'Blue Whale'));    // returns -1

Demo

Yang Zhao

Read more posts by this author.


Comment