indexof 的用途是在一个字符串中寻找一个字的位置
lastindexof 也是找字 , 它们俩的区别是前者从字符串头开始找,后者是从字符串末端开始找。
一但指定的字被找到,就会返回这个字的当前的位置号码。如果没有找到就返回 -1.
var str = //www.stooges.com.my/test/index.aspx123/;console.log(str.indexof(/)); //0console.log(str.lastindexof(/)); //39
参数1是要寻找的字,必须是str,正则不行哦。
此外它还接受第2个参数。number类型, 这个让我们可以指定寻找的范围。
var str = //www.stooges.com.my/test/index.aspx123/;console.log(str.indexof(/, 0)); //0 默认情况是 0console.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)); //20console.log(str.myindexof(/, -2)); //25 倒数第2个的位置