escape a string for use in a regular expression

The following function converts reserved characters into backslash-escaped patterns. This allows a literal string to be used within a regular expression.

escape_for_regexp=(str)->
  return str.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1")

For example:

var literal = "Who said that?";
var escaped = escape_for_regexp(literal); // yields "Who said that\?"
var regexp = new RegExp(escaped);
console.log(regexp);                      // yields /Who said that\?/
Published 19 Jun 2013

 

This page was generated at 9:56 PM on 15 Jan 2016.
Copyright © 1999 - 2016 Rodney Waldhoff.