I’m not sure why, but JavaScript doesn’t appear to have a good way of escaping regular expressions that are provided dynamically. In my case, I was using a string provided as part of a JSON AJAX response, and I realized that it contained a question mark, which has special meaning in a regular expression. Here is my solution:

String.prototype.escapeRegExp = function() {
    var specialChars = [ '$', '^', '*', '(', ')', '+', '[', ']', '{', '}', '\\', '|', '.', '?', '/' ];
    var regex = new RegExp('(\\' + specialChars.join('|\\') + ')', 'g');
    return this.replace(regex, '\\$1');
}

Basically, we modify the string object, adding an escapeRegExp method. It seemed to make more sense to me to add this to the string object and not the RegExp object. Now you can do something like var pattern = new RegExp(dynamicRegex.escapeRegExp(), 'g'); (assuming dynamicRegex is a string object). Then pattern can be passed as the first parameter in a string’s replace method.