indexOf 和 lastIndexOf 使用

indexOf 的用途是在一个字符串中寻找一个字的位置 

lastIndexOf 也是找字 , 它们俩的区别是前者从字符串头开始找,后者是从字符串末端开始找。

一但指定的字被找到,就会返回这个字的当前的位置号码。如果没有找到就返回 -1. 

 var str = "//www.stooges.com.my/test/index.aspx123/";
 console.log(str.indexOf("/")); //0
 console.log(str.lastIndexOf("/")); //39

参数1是要寻找的字,必须是str,正则不行哦。

此外它还接受第2个参数。Number类型, 这个让我们可以指定寻找的范围。

 var str = "//www.stooges.com.my/test/index.aspx123/";
 console.log(str.indexOf("/", 0)); //0 默认情况是 0
 console.log(str.lastIndexOf("/", str.length)); //39 默认情况是 str.length

两个方法的控制是不同方向的 。 

假设 indexOf 设置 10 , 那么查找范围是 从10到str.length(字末)

lastIndexOf 设置 10 的话 , 查找范围会是 从10到 0 (字首) 

这个要注意了。

ps : 设置成负数比如 -500 ,会有奇怪现象,我自己搞不懂 = = " ;

有时我们会希望指定找第n个.那么我们就通过上面的方法来实现了。

比如 : 

   String.prototype.myIndexOf = function (searchValue, startIndex) {             
        var text = this;
        startIndex = startIndex || 1; 
        var is_negative = startIndex < 0;
        var ipos = (is_negative) ? text.length + 1 : 0 - 1; 
        var loopTime = Math.abs(startIndex);
        for (var i = 0; i < loopTime ; i++) {
            ipos = (is_negative) ? text.lastIndexOf(searchValue, ipos - 1) : text.indexOf(searchValue, ipos + 1);
            if (ipos == -1) break;
        }
        return ipos;
    }

        var str = "//www.stooges.com.my/test/index.aspx123/";
        console.log(str.myIndexOf("/", 3)); //20
        console.log(str.myIndexOf("/", -2)); //25 倒数第2个的位置
原文地址:https://www.cnblogs.com/keatkeat/p/3950520.html