这是indexloc提供的服务,不要输入任何密码
Skip to content

Editorial: handle len < seachLen in String.prototype.lastIndexOf #3660

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

mobius29
Copy link

In Step 9 of String.prototype.lastIndexOf, it tries to clamp pos between 0 and len - searchLen and according to clamping, len - searchLen >= 0. So it cannot be defined when len - searchLen < 0.

For example:

"x".lastIndexOf("xy")

Even if clamping were defined to allow cases where the lower bound is greater than the upper bound (i.e., len - searchLen < 0), Step 10 would result in an invalid state. In Step 10, StringLastIndexOf(S, searchStr, start) is invoked with start, which is required to be a non-negative integer. When len < searchLen, the computed start could become negative, which is invalid.

Therefore, this PR adds a step that returns -1 when len < searchLen before Step 9, since it is impossible to find searchString within string when len < searchLen.

@mobius29 mobius29 changed the title Normative: handle len < seachLen in String.prototype.lastIndexOf Editorial: handle len < seachLen in String.prototype.lastIndexOf Jul 24, 2025
Copy link
Member

@linusg linusg left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice find, LGTM. I reported something similar in #3261, I would not be surprised if there are more of these in String.prototype.

@ljharb
Copy link
Member

ljharb commented Jul 24, 2025

Great catch! I updated my polyfill to use the latest algorithm, and it immediately exposed this bug, which this PR fixes.

@ljharb ljharb requested a review from a team July 24, 2025 14:38
ljharb added a commit to es-shims/String.prototype.lastIndexOf that referenced this pull request Jul 24, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants