New Rule: require global regular expression to be used with `replaceAll`
See original GitHub issueRule details
When replaceAll
is given a regular expression as its first argument, that regular expression must be global. If it’s not global, a runtime error is thrown. This rule should require that regular expressions passed as the first argument to replaceAll
are global.
Related ECMAScript feature
String.prototype.replaceAll
: https://github.com/tc39/proposal-string-replaceall
What type of rule is this?
Warns about a potential problem
Example code
`abc`.replaceAll(/a/, ``) // throws Uncaught TypeError: String.prototype.replaceAll called with a non-global RegExp argument
// Should be an error, and could also have an auto-fix to change the code to `abc`.replaceAll(/a/g, ``)
Why should this rule be in the core instead of a plugin?
It prevents a runtime error that’s not otherwise apparent.
Participation
- I am willing to submit a pull request to implement this rule.
Additional comments
It’d be nice to reopen https://github.com/eslint/eslint/issues/12557, too.
Issue Analytics
- State:
- Created 2 years ago
- Comments:5 (3 by maintainers)
Top Results From Across the Web
JavaScript String replace vs replaceAll - Stack Overflow
In other words, when calling replaceAll with a regex literal or RegExp , it must use the global flag. So, there doesn't seem...
Read more >String.prototype.replaceAll() - JavaScript - MDN Web Docs
The replaceAll() method returns a new string with all matches of a pattern ... global flag required when calling replaceAll with regex.
Read more >String.prototype.replaceAll() should not be called ... - DeepScan
This rule applies when a regular expression without the global flag ( g ) is used at String.prototype.replaceAll() .
Read more >43 Regular expressions ( RegExp ) - Exploring JS
A new regular expression is created as specified via pattern . If flags is missing, the empty string '' is used. ... Rules...
Read more >Node.js — String Replace All Appearances - Future Studio
As you can see, using a string as the substring to search for will only replace the first appearance. A regular expression with...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
@bmish, I think that’s different. Maybe for https://github.com/eslint/eslint/issues/12557?
This selector would cover regex literals:
Online Demo