RegExp Escape
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.

Hello!
How is the best way to use the example 2 above? I am confused. I’m showing some tries below, by I believe there’s a better way.
try 1:
var r = new RegExp((new Regexp()).esc(str));
try 2:
var r = new RegExp(str); r.esc(str);
try 3:
var r = new RegExp(str); r.esc();
try 4:
var r = new RegExp.esc(str); // does this work?
I sincerely don’t believe I have to write RegExp or str twice.
I think it’s simpler to use one stand-alone function (not a method), say escapeRE():
var r = new RegExp(escapeRE(str));
Comment by Sony Santos — September 3, 2008 @ 5:00 am
Sony,
As it is currently written, the ‘esc’ function returns a string that must be passed into the instantiation call for RegExp. So you would want to do the following:
var r = new RegExp(RegExp.esc(str));
You could modify ‘esc’ to return the regular expression object, if you wanted to. However, I have written it this way so you can append to the escaped ’str’ before creating a new regular expression.
Comment by Matt Snider — September 5, 2008 @ 12:53 pm
Now I got it, thank you!
Comment by Sony Santos — September 8, 2008 @ 5:24 am