Skip to content
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

Rule proposal: Prefer matchAll #574

Open
brettz9 opened this issue Mar 3, 2020 · 4 comments
Open

Rule proposal: Prefer matchAll #574

brettz9 opened this issue Mar 3, 2020 · 4 comments

Comments

@brettz9
Copy link
Contributor

brettz9 commented Mar 3, 2020

Not offering a PR here, but just thought such a rule could possibly fit your project...

Namely, preferring String.prototype.matchAll to while loop exec assignments.

As per https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll#Examples , one can replace this:

let match;
while ((match = regexp.exec(str)) !== null) {
}

..with the likes of:

for (const match of str.matchAll(regexp)) {
}

I find it quite a bit more elegant and semantic, and it allows avoiding defining a variable in the parent block.

If not, no worries, just thought I'd see if it might pique the interest of others.

@sindresorhus sindresorhus changed the title Prefer matchAll Rule proposal: Prefer matchAll Mar 3, 2020
@sindresorhus
Copy link
Owner

I like it, but the rule needs to be off by default for now as .matchAll requires Node.js 12.

@sindresorhus
Copy link
Owner

This is now accepted. PR welcome :)

@aggmoulik
Copy link

Can anyone please provide some test cases for the same ?

@brettz9
Copy link
Contributor Author

brettz9 commented Jan 15, 2024

Sorry for the delayed reply. Re: test cases, I can mostly just think of the failing case in the OP (and its reverse while (null !== (match = regexp.exec(str))) {), as well as this being left as is (passing):

let match;
while ((match = regexp.exec(str)) !== null) {
  // ...
}
return match; // If `match` is used outside of the block, do not report/fix

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants