2 regexp snippets

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

 

Cheat Sheet for JavaScript Regular Expressions

flags

  • /pattern/g - global
  • /pattern/i - case-insensitive
  • /pattern/m - multi-line

patterns

  • \s - any whitespace character ([\f\n\r\t\v\u00A0\u2028\u2029])
  • \S - any non-whitespace character ([^\f\n\r\t\v\u00A0\u2028\u2029])
  • [\s\S] - commonly used for "anything including newlines (alternative [^])
  • \S - any non-whitespace character ([^\f\n\r\t\v\u00A0\u2028\u2029])

  • \w - any word character (alpha, numeric or underscore) ([a-zA-Z0-9_])

  • \W - any non-word character ([^a-zA-Z0-9_])
  • \d - any digit ([0-9])
  • \D - any non-digit ([^0-9])
  • \cX- control character X (e.g. \cM matches control-M (^M))
  • \b - word boundary (the position between a word char and whitespace)
  • \B - not a word boundary ([^\b]).
  • \xhh - the character with hex code hh
  • \uhhhh - the character with hex code hhhh
Published 18 Jan 2013

 

This page was generated at 4:16 PM on 26 Feb 2018.
Copyright © 1999 - 2018 Rodney Waldhoff.