Snippets are tiny notes I've collected for easy reference.
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
Snippets are tiny notes I've collected for easy reference.