53

问答题 53 /85

请实现javascript中的indexOf功能,判断一个字符串a中是否包含另一个字符串b。
a)如果包含,需要返回匹配字符串b的位置
b)如果不包含,需要返回-1
例如 indexOf("hello","el") returns 1;

参考答案

function indexOf(strA, strB) {
    var lenA = strA.length,
        lenB = strB.length;
    if (lenA < lenB) {
        return -1;
    } else if (lenA == lenB) {
        return 0;
    } else {
        for (var j = 0; j < lenA; j++) {
            if (strA.charAt(j) == strB[0] && strA.substr(j, lenB) == strB) {
                return j;
            }
        }
        return -1;
    }
}
console.log(indexOf("hello", "el")); //1