0

0

js实现prototype扩展的方法(字符串,日期,数组扩展)_javascript技巧

php中文网

php中文网

发布时间:2016-05-16 15:19:48

|

1327人浏览过

|

来源于php中文网

原创

本文实例讲述了js实现prototype扩展的方法。分享给大家供大家参考,具体如下:

String.prototype.isEmpty = function () { return !(/.?[^/s ]+/.test(this)); } //检测字符串是否为空
// 替换字符
String.prototype.reserve = function(type) {
 if (type == 'int') return this.replace(/^/d/g, ''); // 替换字符串中除了数字以外的所有字符
 else if (type == 'en') return this.replace(/[^A-Za-z]/g, ''); // 替换字符串中除了英文以外的所有字符
 else if (type == 'cn') return this.replace(/[^/u4e00-/u9fa5/uf900-/ufa2d]/g, ''); // 替换字符串中除了中文以外的所有字符
 else return this;
}
// 字符串反转
String.prototype.reverse = function() {
 return this.split('').reverse().join('');
}
// 以一个中文算两个字符长度计算字符串的长度
String.prototype.cnLength = function() { return this.replace(/[^/x00-/xff]/g, ' * * ' ).length; }
// 替换字符串中的空格
String.prototype.trim = function(type, char) {
 var type = type ? type.toUpperCase() : '';
 switch (type) {
  case 'B' : // 替换所有欲清除字符,未定义char则默认为替换空格
   return this.replace(char ? new RegExp(char, 'g') : /(/s+| )/g, '');
  case 'O' : // 将两个以上的连续欲清除字符替换为一个,未定义char则默认为替换空格
   return char ? this.replace(new RegExp(char + '{2,}', 'g'), char) : this.replace(/[/s ]{2,}/g, ' ');
  case 'L' : // 替换除左边欲清除字符,未定义char则默认为替换空格
   return this.replace(char ? new RegExp('^(' + char + ') * ', 'g') : /^(/s| ) * /g, '');
  case 'R' : // 替换除右边欲清除字符,未定义char则默认为替换空格
   return this.replace(char ? new RegExp('(' + char + ') * $', 'g') : /(/s| ) * $/g, '');
  default : // 替换除左右两边欲清除字符,未定义char则默认为替换空格
   return this.replace(char ? new RegExp('^(' + char + ') * |(' + char + ') * $', 'g') : /(^/s * | )|( |/s * $)/g, '');
 }
}
// 判断字符串是否是数字
String.prototype.isNumer = function(flag) {
 if (isNaN(this)) {return false;}
 switch (flag) {
  case '+' : return /(^/+?|^/d?)/d * /.?/d+$/.test(this); // 正数
  case '-' : return /^-/d * /.?/d+$/.test(this); // 负数
  case 'i' : return /(^-?|^/+?|/d)/d+$/.test(this); // 整数
  case '+i' : return /(^/d+$)|(^/+?/d+$)/.test(this); // 正整数
  case '-i' : return /^-/d+$/.test(this); // 负整数
  case 'f' : return /(^-?|^/+?|^/d?)/d * /./d+$/.test(this); // 浮点数
  case '+f' : return /(^/+?|^/d?)/d * /./d+$/.test(this); // 正浮点数
  case '-f' : return /^-/d * /./d$/.test(this); // 负浮点数
  default : return true; // 缺省
 }
}
// 仿PHP的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;
 }
}
// 获取url对应参数的值
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;
}
// 判断是否是日期格式(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;
}
// 将字符串转为日期
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;
}
// 格式化日期, 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;
}
// 添加日期,对应参数分别是:类型(y-年, q-季, m-月, w-周, d-日, h-时, i-分, s-秒)和增加的值
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());
 }
}
// 计算两个日期
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();
 }
}
// 判断对象是否是数组
Object.prototype.isArray = function() {return Object.prototype.toString.apply(this) == '[object 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;
}
// 在数组中查找元素并返回第一次出现的位置索引,未找到则返回-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}) 得到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}) 判断是否数组中有一个元素小于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}) 判断是否数组中所有的元素都大于0
Array.prototype.all = function(c) {
 for(var i = 0; i < this.length; i++) {
  if (!c(this)) return false;
 }
 return true;
}
// 移除数组指定的元素,如果指定了limit,则仅移除limit个指定元素,如果省略limit或者其值为0,则所有指定元素都会被移除。
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;
}
// 移除数组中重复的元素
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)} // 求数组中最小值
Array.prototype.max = function() {return Math.max.apply(null, this)} // 求数组中最大值

更多关于JavaScript扩展相关内容感兴趣的读者可查看本站专题:《JavaScript扩展技巧总结

希望本文所述对大家JavaScript程序设计有所帮助。

Narration Box
Narration Box

Narration Box是一种语音生成服务,用户可以创建画外音、旁白、有声读物、音频页面、播客等

下载

相关文章

java速学教程(入门到精通)
java速学教程(入门到精通)

java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

js

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
php源码安装教程大全
php源码安装教程大全

本专题整合了php源码安装教程,阅读专题下面的文章了解更多详细内容。

7

2025.12.31

php网站源码教程大全
php网站源码教程大全

本专题整合了php网站源码相关教程,阅读专题下面的文章了解更多详细内容。

4

2025.12.31

视频文件格式
视频文件格式

本专题整合了视频文件格式相关内容,阅读专题下面的文章了解更多详细内容。

7

2025.12.31

不受国内限制的浏览器大全
不受国内限制的浏览器大全

想找真正自由、无限制的上网体验?本合集精选2025年最开放、隐私强、访问无阻的浏览器App,涵盖Tor、Brave、Via、X浏览器、Mullvad等高自由度工具。支持自定义搜索引擎、广告拦截、隐身模式及全球网站无障碍访问,部分更具备防追踪、去谷歌化、双内核切换等高级功能。无论日常浏览、隐私保护还是突破地域限制,总有一款适合你!

7

2025.12.31

出现404解决方法大全
出现404解决方法大全

本专题整合了404错误解决方法大全,阅读专题下面的文章了解更多详细内容。

42

2025.12.31

html5怎么播放视频
html5怎么播放视频

想让网页流畅播放视频?本合集详解HTML5视频播放核心方法!涵盖<video>标签基础用法、多格式兼容(MP4/WebM/OGV)、自定义播放控件、响应式适配及常见浏览器兼容问题解决方案。无需插件,纯前端实现高清视频嵌入,助你快速打造现代化网页视频体验。

4

2025.12.31

关闭win10系统自动更新教程大全
关闭win10系统自动更新教程大全

本专题整合了关闭win10系统自动更新教程大全,阅读专题下面的文章了解更多详细内容。

3

2025.12.31

阻止电脑自动安装软件教程
阻止电脑自动安装软件教程

本专题整合了阻止电脑自动安装软件教程,阅读专题下面的文章了解更多详细教程。

3

2025.12.31

html5怎么使用
html5怎么使用

想快速上手HTML5开发?本合集为你整理最实用的HTML5使用指南!涵盖HTML5基础语法、主流框架(如Bootstrap、Vue、React)集成方法,以及无需安装、直接在线编辑运行的平台推荐(如CodePen、JSFiddle)。无论你是新手还是进阶开发者,都能轻松掌握HTML5网页制作、响应式布局与交互功能开发,零配置开启高效前端编程之旅!

2

2025.12.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
WEB前端教程【HTML5+CSS3+JS】
WEB前端教程【HTML5+CSS3+JS】

共101课时 | 8.1万人学习

JS进阶与BootStrap学习
JS进阶与BootStrap学习

共39课时 | 3.1万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号