Escaping RegExp Characters Function

If you use regular expressions on your site, then I am sure you have encountered situations where you use a String value, possibly returned from the some user input, as part of your regular expressions. The syntax you might use:

Example 1: Typical Syntax

var haystack = Hello World, my name is NAME!;
var needle = NAME;
var rx = new RegExp(needle);
alert(haystack.replace(rx, Matt Snider));

This very simple example shows how you create a RegExp Object from a String, and use that regex to find and replace a substring of the haystack String. This works great, as long as the needle String does not contain any regex special characters, such as: /, ., *, +, ?, |, (, ), [, ], {, }, \. If the needle contains any of these characters, your regex will return unexpected results or possibly throw an error.

Suppose we have the following situation: you have a large page of text, at the top of which there is an input Element tied to a JavaScript Function that search the pages text, counting the number of times the provided String occurs. The user then wonders how many sentences are in your text, so they do a search for .. The rx variable of the JavaScript Function, actually becomes the regular expression, /./, which matches all characters in the text, instead of just the periods. What we need is a method to escape the text before creating a regular expression:

Example 2: RegExp Escape

var RegExp.esc = function(text) {
  if (! arguments.callee.sRE) {
	var specials = [/, ., *, +, ?, |, (, ), [, ], {, }, \\ ];
	arguments.callee.sRE = new RegExp((\\ + specials.join(|\\) + ), g);

  return text.replace(arguments.callee.sRE, \\$1);

Example 2 searches the text and properly escapes all regular expressions. I did not write this method and am not sure where it came from, but it is effective and fast. Lastly, we need a count method extending the prototype of a RegExp Object to return the number of times the current regular expression matches a haystack String:

Example 3: SubString Count

RegExp.prototype.count = function(haystack) {
	return (haystack || ).match(this).length;

Now using these last two methods in conjunction we can search the text and properly count the number of times that period or other special characters occur, see Test Page for a full text count example.