nzakas / understandinges6

Content for the ebook "Understanding ECMAScript 6"
5.45k stars 796 forks source link

Chapter 2: Strings - start index and 2nd argument for endsWith() method #442

Closed ronen-e closed 3 years ago

ronen-e commented 4 years ago

With regards to the comment from @chaoobject001 : https://github.com/nzakas/understandinges6/issues/401#issuecomment-361010176

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

  1. 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

  2. The start position to search from is: len - searchString.length

  3. 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"

Originally posted by @ronen-e in https://github.com/nzakas/understandinges6/issues/401#issuecomment-589612958