方法1,通过正则的方式
~function(){
let myIndex = function(str) {
let reg = new RegExp(str),
res = reg.exec(this);
return res === null? -1 : res.index;
}
String.prototype.myIndex = myIndex
}()
方法2,普通的for循环
~function(
let myIndex = function(str) {
let lenT = str.length,
lenS = this.length,
res = -1;
if(lenT > lenS) {
return -1;
}
for(let i = 0;i<=lenS - lenT;i++){
if(this.slice(i,lenT+i) === str){
res = i;
break;
}
}
return res;
}
String.prototype.myIndex = myIndex
){}()