Home > Article > Web Front-end > IndexOf and lastIndexOf usage examples introduction_javascript skills
The purpose of indexOf is to find the position of a word in a string
lastIndexOf is also a word search. The difference between them is that the former starts from the beginning of the string and the latter starts from the end of the string.
Once the specified word is found, the current position number of the word will be returned. If not found, return -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 to be searched for, it must be str, regular expression will not work.
Also it accepts the 2nd parameter. Number type, this allows us to specify the search range.
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
The control of the two methods is in different directions.
Assume indexOf is set to 10, then the search range is from 10 to str.length (end of character)
If lastIndexOf is set to 10, the search range will be from 10 to 0 (prefix)
You should pay attention to this.
ps: If it is set to a negative number such as -500, there will be strange phenomena that I can’t understand myself = = " ;
Sometimes we want to specify the nth one. Then we can achieve it through the above method.
For example:
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个的位置