0

I don't understand this behavior of indexOf() and lastIndexOf():

let foo = 'A';
foo.indexOf(''); // 0
foo.lastIndexOf(''); // 1

Based on the indexOf() result, I'd guess that an empty string is on either side of the character 'A' - but if that were the case, lastIndexOf() would return 2 instead of 1. What's going on here?

nCardot
  • 5,992
  • 6
  • 47
  • 83
  • The empty string "appears" at the beginning and end of the string; it's *empty*, so it exists between every character. – Pointy Nov 20 '21 at 18:12
  • likewise with the dupe - its formalized – Daniel A. White Nov 20 '21 at 18:12
  • @Pointy That's what I thought at first, but then wouldn't you get 2 as the ('A').lastIndexOf(''), with the empty string before and after 'A'? – nCardot Nov 20 '21 at 18:17
  • Well there is no index 2 in "A" – Pointy Nov 20 '21 at 18:18
  • There's no index 1 in 'A' either but the empty string is found at index 1. I don't know why it's not ([''][A]['']) with index 2 being the last empty string – nCardot Nov 20 '21 at 18:22
  • 1
    The specification of `.lastIndexOf()` specifically says that if there's no starting position passed in as an argument, and the search string is the empty string, then the result is the length of the string. The length of "A" is 1. – Pointy Nov 20 '21 at 18:31
  • I think you're referring to this part in the spec: "If position [called fromIndex on MDN] is undefined, the length of the String value is assumed, so as to search all of the String." On the MDN page for lastIndexOf it has "If searchValue is an empty string, then fromIndex is returned." But it has "The default value is +Infinity" as the default for position/fromIndex. Maybe MDN should be edited to clarify. – nCardot Nov 20 '21 at 18:50
  • I submitted a pull request to clarify this on the MDN page: https://github.com/mdn/content/pull/10662 – nCardot Nov 20 '21 at 19:04

0 Answers0