eslint-plugin-regexp icon indicating copy to clipboard operation
eslint-plugin-regexp copied to clipboard

Unexpected `regexp/no-useless-escape` report with `RegExp` constructor

Open JounQin opened this issue 3 months ago • 3 comments

Information:

  • ESLint version: v8.48.0
  • eslint-plugin-regexp version: v2.2.0

Description

new RegExp('[\\.]')

It's definitely different with new RegExp('[\.]').

JounQin avatar Mar 07 '24 08:03 JounQin

On the playground, the auto fix wants to simplify it to new RegExp('[.]'), which is correct.

image

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 avatar Mar 07 '24 10:03 RunDevelopment

@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.

JounQin avatar Mar 08 '24 02:03 JounQin

the error is not reported at regexpStr but regexp without source location info, so that's very confusing.

image

As you can see, the error is reported on regexpStr as expected. I think you meant a case like this:

image

Cases where a single string is used by >1 regexes are hard, because errors might not be the same across all regexes. Example:

image

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.

RunDevelopment avatar Mar 09 '24 13:03 RunDevelopment