js implements prototype extension methods of string date array extension

  • 2020-12-05 17:06:10
  • OfStack

This article gives an example of how js implements the prototype extension. To share for your reference, the details are as follows:


String.prototype.isEmpty = function () { return !(/.?[^/s ]+/.test(this)); } // Checks if the string is empty 
//  Substitution characters 
String.prototype.reserve = function(type) {
 if (type == 'int') return this.replace(/^/d/g, ''); //  Replaces all characters in a string except numbers 
 else if (type == 'en') return this.replace(/[^A-Za-z]/g, ''); //  Replaces all characters in the string except English 
 else if (type == 'cn') return this.replace(/[^/u4e00-/u9fa5/uf900-/ufa2d]/g, ''); //  Replaces all characters in the string except Chinese 
 else return this;
}
//  String inversion 
String.prototype.reverse = function() {
 return this.split('').reverse().join('');
}
//  In order to 1 The length of a string is calculated by two characters 
String.prototype.cnLength = function() { return this.replace(/[^/x00-/xff]/g, ' * * ' ).length; }
//  Replaces Spaces in a string 
String.prototype.trim = function(type, char) {
 var type = type ? type.toUpperCase() : '';
 switch (type) {
  case 'B' : //  Replaces all characters to be cleared , undefined char The default is to replace Spaces 
   return this.replace(char ? new RegExp(char, 'g') : /(/s+| )/g, '');
  case 'O' : //  Replace two or more consecutive to clear characters with 1 a , undefined char The default is to replace Spaces 
   return char ? this.replace(new RegExp(char + '{2,}', 'g'), char) : this.replace(/[/s ]{2,}/g, ' ');
  case 'L' : //  Replace the left side to clear the character , undefined char The default is to replace Spaces 
   return this.replace(char ? new RegExp('^(' + char + ') * ', 'g') : /^(/s| ) * /g, '');
  case 'R' : //  Replace divide the right to clear the character , undefined char The default is to replace Spaces 
   return this.replace(char ? new RegExp('(' + char + ') * $', 'g') : /(/s| ) * $/g, '');
  default : //  Replace divide left and right sides to clear characters , undefined char The default is to replace Spaces 
   return this.replace(char ? new RegExp('^(' + char + ') * |(' + char + ') * $', 'g') : /(^/s * | )|( |/s * $)/g, '');
 }
}
//  Determines if a string is a number 
String.prototype.isNumer = function(flag) {
 if (isNaN(this)) {return false;}
 switch (flag) {
  case '+' : return /(^/+?|^/d?)/d * /.?/d+$/.test(this); //  A positive number 
  case '-' : return /^-/d * /.?/d+$/.test(this); //  A negative number 
  case 'i' : return /(^-?|^/+?|/d)/d+$/.test(this); //  The integer 
  case '+i' : return /(^/d+$)|(^/+?/d+$)/.test(this); //  Positive integer 
  case '-i' : return /^-/d+$/.test(this); //  Negative integer 
  case 'f' : return /(^-?|^/+?|^/d?)/d * /./d+$/.test(this); //  Floating point Numbers 
  case '+f' : return /(^/+?|^/d?)/d * /./d+$/.test(this); //  Are floating point Numbers 
  case '-f' : return /^-/d * /./d$/.test(this); //  Negative floating point number 
  default : return true; //  The default 
 }
}
//  imitation PHP the str_pad
String.prototype.pad = function (input, length, type) {
 if (!input) return this;
 if (!length || length < 1) var length = 1;
 var input = Array(length + 1).join(input), value;
 var type = type ? type.toUpperCase() : '';
 switch (type) {
  case 'LEFT' : return input + this;
  case 'BOTH' : return input + this + input;
  default : return this + input;
 }
}
//  To obtain url The value of the corresponding parameter 
String.prototype.getQuery = function(name) {
 var reg = new RegExp('(^|&)' + name + ' = ([^&] * )(&|$)');
 var r = this.substr(this.indexOf('/?') + 1).match(reg);
 return r[2]?unescape(r[2]) : null;
}
//  Determine if it is a date format (YYYY-MM-DD YYYY/MM/DD YYYY.MM.DD)
String.prototype.isDate = function() {
 result = this.match(/^(/d{1, 4})(-|//|.)(/d{1, 2})/2(/d{1, 2})$/);
 if (!result) return false;
 var d = new Date(result[1], result[3]-1, result[4])
 var str = d.getFullYear() + result[2] + (d.getMonth() + 1) + result[2] + d.getDate();
 return this == str;
}
//  Converts a string to a date 
String.prototype.toDate = function() {
 var mDate = new Date(Date.parse(str));
 if (isNaN(mDate)) {
  var arr = this.split('-');
  mDate = new Date(arr[0], arr[1], arr[2]);
 }
 return mDate;
}
//  Formatted date , new Date().format('yyyy/mm/dd')
Date.prototype.format = function(format) {
 var format = format.toLowerCase();
 var type = {
  'm+' : this.getMonth()+1,
  'd+' : this.getDate(),
  'h+' : this.getHours(),
  'i+' : this.getMinutes(),
  's+' : this.getSeconds(),
  'q+' : Math.floor((this.getMonth()+3)/3),
  'ms' : this.getMilliseconds()
 }
 if (/(y+)/.test(format)) format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
 for(var k in type) {
  if(new RegExp('('+ k +')').test(format)) {
   format = format.replace(RegExp.$1, RegExp.$1.length==1 ? type[k] : ('00'+ type[k]).substr((''+ type[k]).length));
  }
 }
 return format;
}
//  Add the date and the corresponding parameters are: type (y- years , q- season , m- month , w- weeks , d- day , h- when , i- points , s- seconds ) And the incremental value 
Date.prototype.addDate = function(type, num) {
 var type = type.toLowerCase();
 switch (type) {
  case 's' : return new Date.parse(Date.parse(this) + (1000 * num));
  case 'i' : return new Date.parse(Date.parse(this) + (60000 * num));
  case 'h' : return new Date(Date.parse(this) + (3600000 * num));
  case 'd' : return new Date(Date.parse(this) + (86400000 * num));
  case 'w' : return new Date(Date.parse(this) + ((86400000 * 7) * num));
  case 'm' : return new Date(this.getFullYear(), (this.getMonth()) + num, this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds());
  case 'q' : return new Date(this.getFullYear(), (this.getMonth()) + num * 3, this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds());
  case 'y' : return new Date((this.getFullYear() + num), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds());
 }
}
//  Calculate two dates 
Date.prototype.dateDiff = function(type, date) {
 if (typeof date == 'string') date = date.toDate();
 switch (type) {
  case 's' : return parseInt((date - this) / 1000);
  case 'i' : return parseInt((date - this) / 60000);
  case 'h' : return parseInt((date - this) / 3600000);
  case 'd' : return parseInt((date - this) / 86400000);
  case 'w' : return parseInt((date - this) / (86400000 * 7));
  case 'm' : return (date.getMonth() + 1) + ((date.getFullYear() - this.getFullYear()) * 12) - (this.getMonth() + 1);
  case 'y' : return date.getFullYear() - this.getFullYear();
 }
}
//  Determines if the object is an array 
Object.prototype.isArray = function() {return Object.prototype.toString.apply(this) == '[object Array]';}
//  Determines whether the specified element exists in an array 
Array.prototype.inArray = function (value) {
 if (this.length < 2) return this[0] == value;
 this.sort(function(a) {
  return new RegExp('^' + value).test(a) ? -1 : 1;
 });
 return this[0] == value;
}
//  Find the element in the array and return the value 1 Secondary occurrence of a location index, not found, returned -1 . 
Array.prototype.indexOf = function(string) {
 var len = this.length, i = 0;
 if (len < 2) return this[0] == value ? 0 : -1;
 for (i; i < len; i++) {
  if (this[i] == string) return i;
 }
 return -1;
}
// [1, 2, 3].each(function(x) {return x+1})  get 2, 3, 4
Array.prototype.each = function(c) {
 var ret = [];
 for(var i = 0; i < this.length; i++) {
  ret.push(c(this[i]));
 }
 return ret;
}
// [1, -1, 2].any(function(x) {return x < 0})  Determines if there is any in the array 1 Each element is less than 0
Array.prototype.any = function(c) {
 for(var i = 0; i < this.length; i++) {
  if (c(this)) return true;
 }
 return false;
}
// [1, 2, 3].all(function(x) {return x > 0})  Determines whether all elements in an array are greater than 0
Array.prototype.all = function(c) {
 for(var i = 0; i < this.length; i++) {
  if (!c(this)) return false;
 }
 return true;
}
//  Removes the element specified in the array , If you specify limit, Just remove limit Three specified elements, if omitted limit Or its value is zero 0 , all specified elements are removed. 
Array.prototype.unset = function(string, limit) {
 var len = this.length, i = 0, count = 0;
 for (i; i < len; i++) {
  if (this[i] == string) {
   this.splice(i, 1);
   if (limit && limit > 0) {
    count++;
    if (count == limit) break;
   }
  }
 }
 return this;
}
//  Removes duplicate elements from the array 
Array.prototype.unique = function() {
 var arr = tmp = [], i, len = this.length;
 if (len < 2) return this;
 for (i = 0; i < len; i++) {
  if (tmp[this[i]]) {
   arr.push(this[i]);
   tmp[this[i]] = true;
  }
 }
 return arr;
}
Array.prototype.min = function() {return Math.min.apply(null, this)} //  Find the minimum value in the array 
Array.prototype.max = function() {return Math.max.apply(null, this)} //  Find the maximum value in the array 

For more information about JavaScript extension, see the JavaScript Extension Tips section.

I hope this article has been helpful in JavaScript programming.


Related articles: