Skip to content

Instantly share code, notes, and snippets.

@aMarCruz
Created August 28, 2018 14:30
Show Gist options
  • Select an option

  • Save aMarCruz/58670d97ca53155eab41ce22c021a4f9 to your computer and use it in GitHub Desktop.

Select an option

Save aMarCruz/58670d97ca53155eab41ce22c021a4f9 to your computer and use it in GitHub Desktop.
Escape an string for using with a Regex constructor
function sanitizeForRegex (str) {
return String(str).replace(/(?=[.?*+^$[\]\\(){}|-])/g, '\\')
}
@aMarCruz
Copy link
Author

aMarCruz commented Sep 1, 2025

In 2025, you can use RegExp.prototype.source for this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment