+ 1
J.S. What exactly does 'indexOf' and LastIndexOf' do?
var str = "Please locate where 'locate' occurs!"; var pos = str.indexOf("locate");
4 ответов
+ 12
1. string.indexOf(substr, pos);
It looks for the substr in string, starting from the given position pos, and returns the position where the match was found or -1 if nothing can be found.
For example:
let string = "Sololearn";
console.log(string.indexOf("Solo")); // 0, coz "Solo" was found at the begining
console.log(string.indexOf("solo")); // -1, not found, coz search is case-sensitive
The optional second parameter allows us to search starting from the given position
For example (let's find second occurrence of "ol"):
let string = "Sololearn";
console.log(string.indexOf("ol", 2)); // 3
You can find all occurrences with help of loop and this amazing method (will be task for you).
2. string.lastIndexOf(substr, pos);
This is a similar method that searches from the end of a string to its begining. It would list the occurrence in the reverse order.
For example:
let string = "Sololearn";
console.log(string.lastIndexOf("ol")); // 3
You can read more about this methods on MDN: https://developer.mozilla.org
+ 2
Better try it on code playground, and tell us the output.
+ 1
Index number 7 for the word staring pos of word "locate" . Count from index 0, the first letter from the left.
P l e a s e locate...
0 1 2 3 4 5 6 7
0
output = 7
I got it from w3school and it just didn't make sense: https://www.w3schools.com/js/tryit.asp?filename=tryjs_string_indexof