方法1,通过正则的方式

    1. ~function(){
    2. let myIndex = function(str) {
    3. let reg = new RegExp(str),
    4. res = reg.exec(this);
    5. return res === null? -1 : res.index;
    6. }
    7. String.prototype.myIndex = myIndex
    8. }()

    方法2,普通的for循环

    1. ~function(
    2. let myIndex = function(str) {
    3. let lenT = str.length,
    4. lenS = this.length,
    5. res = -1;
    6. if(lenT > lenS) {
    7. return -1;
    8. }
    9. for(let i = 0;i<=lenS - lenT;i++){
    10. if(this.slice(i,lenT+i) === str){
    11. res = i;
    12. break;
    13. }
    14. }
    15. return res;
    16. }
    17. String.prototype.myIndex = myIndex
    18. ){}()