Skip to Main Content

Escaping Strings for Use in Regular Expressions

I looked around on the web and found a few suggestions, but I like this the best:

String.prototype.escapeRegex = function() {
    return this.toString().replace(/([\[|\\|\^|\$|\.|\||\?|\*|\+|\(|\)])/gm,"\\$1");
};