indexOf 和 lastIndexOf 使用示例介绍
indexOf的用途是在一个字符串中寻找一个字的位置
lastIndexOf也是找字,它们俩的区别是前者从字符串头开始找,后者是从字符串末端开始找。
一但指定的字被找到,就会返回这个字的当前的位置号码。如果没有找到就返回-1.
varstr="//www.stooges.com.my/test/index.aspx123/";
console.log(str.indexOf("/"));//0
console.log(str.lastIndexOf("/"));//39
参数1是要寻找的字,必须是str,正则不行哦。
此外它还接受第2个参数。Number类型,这个让我们可以指定寻找的范围。
varstr="//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){
vartext=this;
startIndex=startIndex||1;
varis_negative=startIndex<0;
varipos=(is_negative)?text.length+1:0-1;
varloopTime=Math.abs(startIndex);
for(vari=0;i<loopTime;i++){
ipos=(is_negative)?text.lastIndexOf(searchValue,ipos-1):text.indexOf(searchValue,ipos+1);
if(ipos==-1)break;
}
returnipos;
}
varstr="//www.stooges.com.my/test/index.aspx123/";
console.log(str.myIndexOf("/",3));//20
console.log(str.myIndexOf("/",-2));//25倒数第2个的位置