Hi coders,
continue with my study on JS and I found this exercise:
Write a function secondIndexOf , taking two strings and determining the second occurrence of the second string in the first string. If the search string does not occur twice, -1 should be returned. secondIndexOf('White Rabbit', 'it') should return 10 .
var secondIndexOf = function(s1, s2 ){
var firstIndex = s1.indexOf(s2);
return s1.indexOf(s2, firstIndex + 1);
};
I have some doubt about this code, because I don’t understand why we have to use twice indexOf()
indexOf has a second possible argument that says at which index the search start at.
indexOf returns the index of the first occurrence of what you are searching
the second use of indexOf (that has also the argument to say at which index the search should start) will start the search after that
I didn’t understand how it uses in the return firstIndex + 1 and why use indexOf () again instead of running once only return.
I tested this code and result is 10 because if I have not misunderstood wrong that return at the number 10 position which is the search for the second string.
Sorry if I wrote my reasoning wrong but I’m not native English and I find it hard to express my logical reasoning.
the first line declares a function that takes two strings as parameters
the second line initializes and declares a varabial that takes the first string parameter ed
starts the search on the second parameter to check if there are any similarities (?)
the third line resumes the first string executes indexOf which in turn takes it as
parameter the second string and the variable increasing it by 1.
I don’t know if my reasoning is correct, because in the documentation it says occurrence, but I don’t know what it is.
If I use only one time indexOf () gives me the result of 2
try seeing if there is the documentation for your language (the MDN pages are written in many different languages), or if there is an online translator that can help you solve the language doubts
so, the second line is initialising a variable called firstIndex - what determines this value?
how is it that value used in the third line?
the variable determines if in the second string there are the same values that in the first string are the same and say in which position they are set.
Instead in the third line compare the first string with second string but take also the first research (firstIndex) that increases by 1 (maybe is it a counter ?)
fromIndex : An integer representing the index at which to start the search
…
But I had used the console.log to see what value was returning firstIndex is telling me 2, how did it get to be 10?
Unless first Index + 1 represents the last position of my string