Unexpected `regexp/no-useless-escape` report with `RegExp` constructor
JounQin opened this issue · comments
Information:
- ESLint version: v8.48.0
eslint-plugin-regexp
version: v2.2.0
Description
new RegExp('[\\.]')
It's definitely different with new RegExp('[\.]')
.
On the playground, the auto fix wants to simplify it to new RegExp('[.]')
, which is correct.
I think the cause of the confusing is that the error message says: Unnecessary escape character: \..
. The message only mentions one backslash because there is only one backslash in contained in the source of the regex. We just need to write one backslash as \\
because of JS string syntax.
In general, we should probably do some kind of source mapping here. E.g. in this case, I think the error message should have been something like: Unnecessary escape character '\.' (written as '\\.' in source code) can be replaced with '.'.
@RunDevelopment The worst thing is when using something like
var regexpStr = '\\.[\\.]'
var regexp = new RegExp(regexpStr)
the error is not reported at regexpStr
but regexp
without source location info, so that's very confusing.
the error is not reported at
regexpStr
butregexp
without source location info, so that's very confusing.
As you can see, the error is reported on regexpStr
as expected. I think you meant a case like this:
Cases where a single string is used by >1 regexes are hard, because errors might not be the same across all regexes. Example:
The regex with the i
flag wants to simplify [Aab]
to [ab]
, but this isn't valid because of the regex without the i
flag.
In general, cases where a string is read by something other than a single RegExp
constructor are difficult to deal with, because there might be good reasons to not change the string.