Nodejs String Trim trim(fag='default')

Here you can find the source of trim(fag='default')

Method Source Code

String.prototype.trim = function (fag='default'){
   const preg_arr = {'default':/(^\s*)|(\s*$)/,'left':/(^\s*)/,'right':/(\s*$)/};
   switch(fag){//from   ww w  .  j  ava 2 s .  c  om
      case 'left':
         return this.replace(preg_arr.left,'');
      break;
      case 'right':
         return this.replace(preg_arr.right,'');
      break;
      default:
         return this.replace(preg_arr.default,'');
      break;
   }
}

String.prototype.ltrim = function (){
   return this.trim('left');
}

String.prototype.rtrim = function (){
   return this.trim('right');
}


//test using
var str = '       swd  dfgdfgn  ';
console.log(str.trim());

Related

  1. trim(c, t)
    String.prototype.trim = function(c, t){
      return c = "[" + (c == undefined ? " " : c.replace(/([\^\]\\-])/g, "\\\$1")) + "]+",
      this.replace(new RegExp((t != 2 ? "^" : "") + c + (t != 1 ? "|" + c + "$" : ""), "g"), "");
    };
    
  2. trim(ch)
    String.prototype.trim = function(ch) {
        var r = new RegExp("^{0}+|{0}+$".format(ch || "\\s"), "g");
        return this.replace(r, "");
    };
    
  3. trim(character)
    String.prototype.trim = function (character) {
      return this.trimLeft(character).trimRight(character);
    };
    
  4. trim(charlist)
    'use strict';
    String.prototype.trim = function (charlist) {
      return this.ltrim(charlist).rtrim(charlist);
    };
    
  5. trim(chars)
    String.prototype.trim = function(chars) {
      return this.replace(new RegExp('^[' + (chars || '\\s') + ']+|[' + (chars || '\\s') + ']+$', 'g'), '');
    };
    
  6. trim(str)
    String.prototype.trim = function(str) {
      str = str.replace(/^\s+/,'');
      for( var i = str.length - 1 ; i >= 0 ; i--) {
        if(/\S/.test(str.charAt(i))) {
            str = str.substring(0,i+1);
            break;
      return str;
    ...
    
  7. trim(str)
    var trim = function (str) {
        return str.replace(/\s*/g, "");
    };
    
  8. trim(ws)
    String.prototype.trim = function (ws)
        if(!this.length) return "";
        var tmp = this.stripNL().ltrim().rtrim();
        if(ws) return tmp.replace(/ +/g, ' ');
        else return tmp;
    String.prototype.rtrim = function ()
        if(!this.length) return "";
        return this.replace(/\s+$/g, '');
    String.prototype.ltrim = function ()
        if(!this.length) return "";
        return this.replace(/^\s+/g, '');
    String.prototype.stripNL = function ()
        if(!this.length) return "";
        return this.replace(/[\n\r]/g, '');
    
  9. trim2()
    String.prototype.trim2 = function() {
      return this.replace(/^\s+|\s+$/g, '');
    };
    String.prototype.trim = function() {
      return this.replace(/^\s+/, '').replace(/\s+$/, '');
    };
    'foo     '.trim(); 
    '     foo'.trim(); 
    '  foo   '.trim(); 
    ...