/**
1、循环原始字符串的每一项,让每一项从当前位置向后截取 H.length 个字符,
然后和 Y 进行比较,如果不一样,继续循环;如果一样返回当前索引即可
**/
function myIndexOf(Y) {
let lenY = Y.length,
lenH = H.length,
res = -1;
if (lenY > lenH) return res;
for (let i = 0; i <= lenH - lenY; i++) {
if (this.substr(i, lenY) === Y) {
res = i;
break;
}
}
return res;
}
String.prototype.myIndexOf = myIndexOf;
let H = 'fighting',
Y = 'ht';
console.log(H.myIndexOf(Y));
/**
2、正则处理
**/
function myIndexOf(Y) {
// this:H
let reg = new RegExp(Y),
res = reg.exec(this);
return res === null ? -1 : res.index;
}
String.prototype.myIndexOf = myIndexOf;
let H = 'fighting',
Y = 'ht';
console.log(H.myIndexOf(Y));