Examples of indexOf and lastIndexOf

  • 2020-03-30 03:50:03
  • OfStack

The purpose of indexOf is to find the position of a word in a string

LastIndexOf is also a word search, and the difference between the two is that the former starts at the head of the string and the latter at the end of the string.

Once the specified word is found, the current location number of the word is returned. If it is not found, it returns negative 1.


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

Parameter 1 is the word you are looking for. It must be STR.

It also accepts a second parameter. Number type, which allows us to specify the range we're looking for.


var str = "//www.stooges.com.my/test/index.aspx123/";
console.log(str.indexOf("/", 0)); //0 is 0 by default
console.log(str.lastIndexOf("/", str.length)); //39  The default is  str.length

The two methods are controlled in different directions.

Assuming indexOf is set to 10, the search range is from 10 to STR. Length (end of word)

With lastIndexOf set to 10, the search range is from 10 to 0.

That's something to watch out for.

Ps: set it to a negative number, such as -500, there will be strange phenomena, I can't understand by myself = = ";

Such as:


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  From the first 2 The position of a 

Related articles: