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

RegExp._escape #11

Open
coolaj86 opened this issue Feb 19, 2022 · 5 comments
Open

RegExp._escape #11

coolaj86 opened this issue Feb 19, 2022 · 5 comments
Labels
std Extends the Standard Library

Comments

@coolaj86
Copy link
Collaborator

coolaj86 commented Feb 19, 2022

Implementation

RegExp._escape = function escapeRegExp(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
};

Good Usage:

new RegExp(escapeRegExp(str), 'g');

Bad Usage:

new RegExp('\\' + escapeRegExp(str), 'g');

Unlikely to ever be accepted into ECMAScript. See:

@coolaj86 coolaj86 added the std Extends the Standard Library label Mar 5, 2022
@DBBrowne
Copy link

What would someone be trying to achieve with the "Bad Usage" pattern?

@coolaj86
Copy link
Collaborator Author

That's the question of the decade isn't it... tc39/proposal-regex-escaping#37 (comment)

@DBBrowne
Copy link

So someone might use the '\\' + escapeRegExp(...) pattern if they were trying to escape a \ at the beginning of their regex?
Which would be unnecessary here, because escaping that initial \ should be handled by the escapeRegEx function?

@coolaj86
Copy link
Collaborator Author

coolaj86 commented Mar 15, 2022

It doesn't make any sense. I couldn't find any explanation of "the even/odd problem", just a reference to it.

I'll summarize it here as well:

You'd have to be stupid to do that. Obviously if you only use an escape on part of your string, only part of your string is escaped. If you use \ then it may escape whatever comes next. If you use \\ then the \ is escaped. If it's a string then \\\ means nothing and \\\\ would mean \\ which, as regex would be a single literal \.

I can't explain it better because it's literally nonsense, which is what everyone is so upset about.

@coolaj86
Copy link
Collaborator Author

coolaj86 commented Mar 15, 2022

(seriously, don't dig too deep trying to understand it, it's lost cause - someone just made up a bad use case and I'm quoting it here not because it would ever make sense, but just to document exactly what was shown to be an invalid use)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
std Extends the Standard Library
Projects
None yet
Development

No branches or pull requests

2 participants