ota-meshi / eslint-plugin-regexp

ESLint plugin for finding regex mistakes and style guide violations.

Home Page:https://ota-meshi.github.io/eslint-plugin-regexp/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

`prefer-lookaround` should ignore `^` and `$`

fisker opened this issue · comments

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?

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.

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.

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')