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

prefer-lookaround should ignore ^ and $ #478

Closed
fisker opened this issue Nov 18, 2022 · 3 comments · Fixed by #480
Closed

prefer-lookaround should ignore ^ and $ #478

fisker opened this issue Nov 18, 2022 · 3 comments · Fixed by #480

Comments

@fisker
Copy link

fisker commented Nov 18, 2022

Information:

  • ESLint version: 8.27.0
  • eslint-plugin-regexp version: 7.31.10

Description

var str = 'JavaScript'.replace(/Java(Script)/g, 'Type$1')
var str = 'JavaScript'.replace(/Java(Script$)/g, 'Type$1')
var str = 'JavaScript'.replace(/Java(Script)$/g, 'Type$1')

The first two are reported, but the 3rd is not.

I think

var str = 'JavaScript'.replace(/Java(?=Script)$/g, 'Type')

should result the same. Will adding support for this case break things?

@RunDevelopment
Copy link
Collaborator

RunDevelopment commented Nov 18, 2022

but the 3rd is not.

Can confirm. This should be reported.

In general, there may be any number of assertions after the capturing group to be replaced. The rule should do this:

-'JavaScript'.replace(/Java(Script)$/g, 'Type$1')
+'JavaScript'.replace(/Java(?=Script$)/g, 'Type')

I think

var str = 'JavaScript'.replace(/Java(?=Script)$/g, 'Type')

should result the same.

It's not, the assertion after the capturing group has to be placed at the end of the new lookahead. Example:

> 'JavaScript'.replace(/Java(Script)$/g, 'Type$1')
'TypeScript'
> 'JavaScript'.replace(/Java(?=Script)$/g, 'Type')
'JavaScript'
> 'JavaScript'.replace(/Java(?=Script$)/g, 'Type')
'TypeScript'

In fact, /Java(?=Script)$/ will always reject.

@fisker
Copy link
Author

fisker commented Nov 19, 2022

It's not, the assertion after the capturing group has to be placed at the end of the new lookahead.

Thank you! You are right.

@fisker
Copy link
Author

fisker commented Nov 19, 2022

So, to summarize

var str = 'JavaScript'.replace(/Java(Script)$/g, 'Type$1')

// ->

var str = 'JavaScript'.replace(/Java(?=Script$)/g, 'Type')

And

var str = 'JavaScript'.replace(/Java(S)(c)(r)(i)(p)(t)/g, 'Type$1$2$3$4$5$6')

// ->

var str = 'JavaScript'.replace(/Java(S)(c)(r)(i)(p)(?=t)/g, 'Type$1$2$3$4$5')

// ->

var str = 'JavaScript'.replace(/Java(S)(c)(r)(i)(?=pt)/g, 'Type$1$2$3$4')

// ...

var str = 'JavaScript'.replace(/Java(?=Script)/g, 'Type')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
2 participants