New rule proposal: prefer-regex-literals
See original GitHub issuePlease describe what the rule should do:
Suggests to use regex literals instead of RegExp()
/new RegExp()
when these calls have:
- One argument that is a string literal.
- Two arguments and they are both string literals.
What category of rule is this? (place an “X” next to just one item)
[X] Suggests an alternate way of doing something (suggestion)
Provide 2-3 code examples that this rule will warn about:
// good, dynamic
new RegExp(pattern);
new RegExp(prefix + "foo");
new RegExp("foo", flags);
// good, regex literals
/^\d\./
/\d\d\.\d\d\.\d\d\d\d/
// bad, this is a very possible error
new RegExp("^\d\.");
new RegExp("\d\d\.\d\d\.\d\d\d\d");
// bad, correct but unreadable
new RegExp("^\\d\\.");
new RegExp("\\d\\d\\.\\d\\d\\.\\d\\d\\d\\d");
Why should this rule be included in ESLint (instead of a plugin)?
I think this is not just a style preference, rather a good practice to avoid an unnecessary level of the string literal syntax on top of the regex syntax. It’s error-prone and difficult to reason about escapes of escapes.
Are you willing to submit a pull request to implement this rule?
Yes.
Issue Analytics
- State:
- Created 4 years ago
- Reactions:4
- Comments:5 (5 by maintainers)
Top Results From Across the Web
prefer-regex-literals - ESLint - Pluggable JavaScript Linter
A pluggable and configurable linter tool for identifying and reporting on patterns in JavaScript. Maintain your code quality with ease.
Read more >SE-0354 (Second Review): Regex Literals - Swift Forums
This proposal introduces a literal syntax for the Regex to the language. It will be run simultaneously with a proposal regarding the syntax...
Read more >ESLint equivalents in Elm - Elmcraft
Comparing ESLint functionality and the equivalents in the Elm ecosystem.
Read more >Is there a RegExp.escape function in JavaScript?
According to ECMA-262, on the one hand, regular expression "syntax characters" are always non-alphanumeric, such that the result is secure, and special escape ......
Read more >regex literal syntax - Google Groups
In other words, under the proposed syntax Clojure regex literals would ... I like both proposed changes: new escape rules for #" ,...
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
That style indeed doesn’t have the problem with double escapes.
First idea was to disallow just string literals (maybe also simple template literals used as strings), but since the rule is
prefer-regex-literals
it might make sense to disallow this style, too?I agree! Working on this.