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

Unexpected regexp/no-useless-escape report with RegExp constructor #701

Open
JounQin opened this issue Mar 7, 2024 · 3 comments
Open

Unexpected regexp/no-useless-escape report with RegExp constructor #701

JounQin opened this issue Mar 7, 2024 · 3 comments
Labels
enhancement New feature or request

Comments

@JounQin
Copy link

JounQin commented Mar 7, 2024

Information:

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

Description

new RegExp('[\\.]')

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

@RunDevelopment
Copy link
Collaborator

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 RunDevelopment added the enhancement New feature or request label Mar 7, 2024
@JounQin
Copy link
Author

JounQin commented Mar 8, 2024

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

@RunDevelopment
Copy link
Collaborator

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants