What I observed is that:
given second argument is provided as X,
when user invokes endsWith()
Then the sub-string to be searched start from index 0 to index {X}
Example:
let msg = "012345678";
console.log(msg.endsWith("23", 4)); // true
The length (len) of the string to work on is treated as the second argument.
If it is omitted then len = msg.length
Note: if endPosition is greater then msg.length then msg.length is used for len
The start position to search from is: len - searchString.length
The search is made from len - searchString.length to len
Needs fix
So the text in the book is contradictory to the specs:
In chapter 2 under "Methods for Identifying Substrings"
When the second argument is provided, includes() and startsWith() start the match from that index while endsWith() starts the match from the second argument;
Suggested text
"while endsWith() starts the match from the second argument, or if omitted, from the length of the string, minus the length of the first argument"
In chapter 2 under "Methods for Identifying Substrings"
The call to msg.endsWith("o", 8) starts the search from index 0 and searches up to index 7, which is the "o" in "world".
Suggested text
The call to msg.endsWith("o", 8) starts the search from index 7 (inclusive) and searches up to index 8 (exclusive), which is the "o" in "world"
With regards to the comment from @chaoobject001 : https://github.com/nzakas/understandinges6/issues/401#issuecomment-361010176
That is not correct according to the specs: https://www.ecma-international.org/ecma-262/10.0/index.html#sec-string.prototype.endswith
and also conflicts with the information found in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
The length (
len
) of the string to work on is treated as the second argument.If it is omitted then
len = msg.length
Note: if endPosition is greater thenmsg.length
thenmsg.length
is used forlen
The start position to search from is:
len - searchString.length
The search is made from
len - searchString.length
tolen
Needs fix
So the text in the book is contradictory to the specs:
In chapter 2 under "Methods for Identifying Substrings"
Suggested text
"while endsWith() starts the match from the second argument, or if omitted, from the length of the string, minus the length of the first argument"
In chapter 2 under "Methods for Identifying Substrings"
Suggested text
The call to
msg.endsWith("o", 8)
starts the search from index 7 (inclusive) and searches up to index 8 (exclusive), which is the "o" in "world"Originally posted by @ronen-e in https://github.com/nzakas/understandinges6/issues/401#issuecomment-589612958