Reputation:
In the following snippet, what role does pos = string.indexOf( 'e', pos + 1 )
play?
var string = 'To be, or not to be, that is the question';
var count = 0;
var pos = string.indexOf('e');
while ( pos !== -1 ) {
count++;
pos = string.indexOf( 'e', pos + 1 )
}
console.log(count);
Upvotes: 0
Views: 80
Reputation: 3356
The
indexOf()
method returns the position of the first occurrence of a specified value in a string.
Syntax :
string.indexOf(searchvalue,start)
Return a Number, representing the position where the specified searchvalue
occurs for the first time, or -1 if it never occurs
var str = "To be, or not to be, that is the question";
var n = str.indexOf("e", 5);
The above code returns the first occurrence of the letter "e" in a string, starting the search at position 5:
For more : Click here
Note: The indexOf()
method is case sensitive.
Upvotes: 1
Reputation: 5357
The second parameter of the indexOf
function is the index you want to start to look in the string
As you can see in here
str.indexOf(searchValue[, fromIndex])
If you didn't use the secondParam in that case, you would be getting the position of the first 'e' forever. This function is counting the numbers of 'e's in that phrase.
Upvotes: 2
Reputation: 508
The second argument in string.indexOf is the index of the string to start searching from.
All this code does is count the number of e's in the sentence.
Upvotes: 1
Reputation: 9846
From the docs, indexOf
takes an additional parameter:
fromIndex (Optional)
The index at which to start the searching forwards in the string. It can be any integer. The default value is 0, so the whole array is searched. If fromIndex < 0 the entire string is searched. If fromIndex >= str.length, the string is not searched and -1 is returned. Unless searchValue is an empty string, then str.length is returned.
Judging purely from this information, the behaviour of the program as a whole is easily deduced:
e
appears in the string overall, using string.indexOf
to find each occurence.string.indexOf
only returns the position of the first occurence of the character in the string. By passing and updating fromIndex
with the value of pos
, string.indexOf
finds all subsequent occurences of e
by ignoring characters before pos
.
A counter is updated each time it does so, allowing the program as a whole to compute the number of times e
appears in the string.
Upvotes: 2