Dynamically Escape Regular Expressions In JavaScript

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.

About Ian G. Clifton

He served in the USAF and earned his secondary level teaching certification in Washington State. After that, he worked as a web developer and then as a mobile app developer, specializing in Android. He currently works in Seattle, WA as an Android developer and spends his off time on photography, drawing, developing, and doing technical review for other Android developers. You can follow his posts on this blog or his ramblings on Twitter.
This entry was posted in JavaScript and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>