Nodejs Regexp Escape escape()

Here you can find the source of escape()

Method Source Code

/*//w ww . j a  v  a  2 s .c o  m
 * Helpers for escaping new regexp
 */

function escapeRegExp(str) {
    return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
}

function unEscapeRegExp(str) {
    return str.replace(/\\(?!\\)/g,'');
}

// attach to RegExp constructor
RegExp.escape = escapeRegExp;

// attach to RegExp prototype as "escape()" method
RegExp.prototype.escape = function(){
    var flags = (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : '') + (this.multiline ? 'm' : ''); // TODO: implement this.lastIndex
    return new RegExp(escapeRegExp(this.source), flags);
};

// attach to String prototype as "escape()" method
String.prototype.escape = function(){
    return escapeRegExp(this);
};

// attach to String prototype as "unescape()" method
String.prototype.unescape = function(){
    return unEscapeRegExp(this);
};

Related

  1. escape(text)
    RegExp.escape = function(text) {
      return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    };
    
  2. escapeRegExp()
    String.prototype.escapeRegExp = function() {
      return this.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
    };
    
  3. escapeRegExp(string)
    String.prototype.escapeRegExp = function(str) {
      return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
    
  4. escapeRegExp(string)
    function escapeRegExp(string) {
      return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");