Closed JansenZ closed 6 years ago
Yes you are right, when the example is changed to
var message = "hellm world";
message.endsWith('o', 8); // prints true in console
On page 20: "endsWith() starts the match from the length of the string minus the second argument" This statement may be contradicting https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith and what I observed in browser console
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
Thanks, that’s definitely a mistake. I’ll get that fixed.
With regards to the comment from @chaoobject001 :
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
That is not correct according to the specs: https://www.ecma-international.org/ecma-262/10.0/index.html#sec-string.prototype.endswith
String.prototype.endsWith ( searchString [ , endPosition ] )
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 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
So the text in the book is contradictory to the specs:
When the second argument is provided,
includes()
andstartsWith()
start the match from that index whileendsWith()
starts the match from the second argument;
"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"
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".
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"
MDN say If provided overwrites the considered length of the string to search in. If omitted, the default value is the length of the string.
which means
this o is not o in 'hello'; this o is o in 'world';