1

Does anyone have an existing, proven javascript method that will convert a plain text string to its equivalent regex string, with escapes ('\' added for all of the regex control characters?

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125

1 Answers1

1

This is a very common overlooked problem. I hope this routine helps.

   /** add escapes for regexp special characters to turn plainText into a verbatim regexp string
    *
    * @param plainText plain text string that may contain characters that need to be escaped to become a regexp
    * @returns {string} modified string that will work within a regexp
    */
   regexpEscape: function (plainText) {
       //noinspection JSLint
       return plainText.replace(/([-()\[\]{}+?*.$\^|,:#<!\/\\])/g, '\\$1');
   },
bret
  • 796
  • 9
  • 5