Skip to content

Instantly share code, notes, and snippets.

@keego
Created November 30, 2022 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keego/b0449a5ee0074f22303761062fa8955a to your computer and use it in GitHub Desktop.
Save keego/b0449a5ee0074f22303761062fa8955a to your computer and use it in GitHub Desktop.
const syntaxChars = /[\^$\\.*+?()[\]{}|]/g
/**
* Escapes all special special regex characters in a given string
* so that it can be passed to `new RegExp(escaped, ...)` to match all given
* characters literally.
*
* inspired by https://github.com/es-shims/regexp.escape/blob/master/implementation.js
*
* @param {string} s
*/
export function escape(s) {
return s.replace(syntaxChars, '\\$&')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment