Skip to content

Enhancement: [prefer-regexp-exec] option or rule for preferring string.match over regexp.exec #11434

@AmeroHan

Description

@AmeroHan

Before You File a Proposal Please Confirm You Have Done The Following...

My proposal is suitable for this project

  • I believe my proposal would be useful to the broader TypeScript community (meaning it is not a niche proposal).

Link to the rule's documentation

https://typescript-eslint.io/rules/prefer-regexp-exec

Description

As the description of prefer-regexp-exec goes, "keeping to consistently using one of the two can help improve code readability".

function getBearer(headers: Headers): string | undefined {
  return headers.get('Authorization')?.match(/^Bearer (.+)$/)?.[1]
}

// somewhere else
console.log(/thing/.exec('something'))

We cannot turn both of them into regexp.exec(string) as there is an optional chain. However, they can be turned into string.match(regexp). It is more often for strings compared to RegExps to be optional.

While RegExp#exec might be ssssslightly faster than String#match, it doesn't matter for most projects.

Fail

/thing/.exec('something')

Pass

'something'.match(/thing/)

Additional Info

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement: plugin rule optionNew rule option for an existing eslint-plugin rulepackage: eslint-pluginIssues related to @typescript-eslint/eslint-plugintriageWaiting for team members to take a look

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions