Escape RegExp

OSCC · JavaScript, String, Regexp · Sep 15, 2020

Escapes a string to use in a regular expression.

const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
escapeRegExp('(test)'); // \\(test\\)

Recommended snippets

  • Escape HTML

    JavaScript, String

    Escapes a string for use in HTML.

  • Unescape HTML

    JavaScript, String

    Unescapes escaped HTML characters.

  • Word wrap string

    JavaScript, String

    Wraps a string to a given number of characters using a string break character.