这些原型方法有一部分是之前项目的一位大佬写的,还有一部分是其他项目中用到,自己网上搜罗的,正好今天闲比较闲,想起来整理到一起记录一下。这个文件一般可以直接复制到项目中,用来做utils 文件,里边包含了 Date , Number, String, Array 对象上封装的常用方法,具体请看注释!如果要拿去做项目的 utils 文件,可以把这些方法写在一个立即执行函数中,避免污染全局空间!
function Utils() {};
/*
* 格式化金额
* @param money [string/Number] 待精确的金额
* @param precision [int] 小数点后精确位数 默认:4
* e.g.: 1234567.89 => 1,234,567.8900
*/
Utils.prototype.formatMoney = function (money, precision) {
var decimal, formatRound, i, round, temp;
if (precision == null) {
precision = 4;
}
formatRound = function (money) {
return ("" + money).replace(/(\d+?)(?=(?:\d{3})+$)/g, '$1,');
};
money = money + '';
temp = money.split('.');
round = +temp[0];
round = formatRound(round);
if (!precision) {
return round;
}
decimal = '' + Math.round(("." + (temp[1] || 0)) * Math.pow(10, precision));
return (formatRound(round)) + "." + (((function () {
var ref, results;
results = [];
for (i = 0, ref = precision - decimal.length; i < ref; i++) {
results.push('0');
}
return results;
})()).join('')) + decimal;
};
window.Utils = new Utils();
// console.log(Utils.formatMoney(12345677.8888,6))
/*
* 获得指定日期、时间规范格式<yyyy-MM-dd>|<HH:mm:ss>|<yyyy-MM-dd HH:mm:ss>的字符串
* @param param [Object] 选填。JSON对象。
* @param param - date [Date] 选填。欲格式化的Date类型的数据。如为空,则默认当前日期。
* @param param - hasDate [Boolean] 选填。返回的规范化字符串带有“日期”。
* @param param - hasTime [Boolean] 选填。返回的规范化字符串带有“时间”。
* @param param - forward [Number] 选填。提前的天数。支持0和负整数。如果调用时带有此参数,将返回一个包含两个元素的数组,第一个日期早于第二个日期。
* 注:此函数是用来追加到Date prototype的,不能直接调用。
*/
_formatDate = function (param) {
var H, M, d, date, hD, hT, m, rD, rT, re, s, y;
date = param['date'] || this;
y = date.getFullYear();
M = date.getMonth() + 1;
M = (M + '').length > 1 ? M : '0' + M;
d = date.getDate();
d = (d + '').length > 1 ? d : '0' + d;
H = date.getHours();
H = (H + '').length > 1 ? H : '0' + H;
m = date.getMinutes();
m = (m + '').length > 1 ? m : '0' + m;
s = date.getSeconds();
s = (s + '').length > 1 ? s : '0' + s;
hD = param.hasDate;
hT = param.hasTime;
rD = hD ? y + '-' + M + '-' + d : '';
rT = hT ? H + ':' + m + ':' + s : '';
re = "" + rD + (hD && hT ? ' ' : '') + rT;
date = void 0;
return re;
};
/*
* 获得指定月份第一天的规范格式<yyyy-MM-dd>的字符串
* @param date [Date/String] 必填。指定月份的Date对象或可以转换成Date对象的字符串
*/
_firstDayOfMonth = function (date) {
if (typeof date === 'string') {
date = new Date(date);
}
return new Date(date.setDate(1));
};
/*
* 获得指定月份最后一天的规范格式<yyyy-MM-dd>的字符串
* @param date [Date/String] 必填。指定月份的Date对象或可以转换成Date对象的字符串
*/
_lastDayOfMonth = function (date) {
var re;
if (typeof date === 'string') {
date = new Date(date);
}
date = new Date(date.setDate(1));
re = date.setMonth(date.getMonth() + 1) - 1 * 24 * 60 * 60 * 1000;
return new Date(re);
};
/*
* 获取格式化日期:2000-01-01
*/
Date.prototype.getFormatDate = function (date) {
if (date == null) {
date = this;
}
return _formatDate.call(this, {
date: date,
hasDate: 1
});
};
/*
* 获取格式化时间:00:00:00
*/
Date.prototype.getFormatTime = function (date) {
if (date == null) {
date = this;
}
return _formatDate.call(this, {
date: date,
hasTime: 1
});
};
/*
* 获取格式化日期+时间:2000-01-01 00:00:00
*/
Date.prototype.getFormatDateAndTime = function (date) {
if (date == null) {
date = this;
}
return _formatDate.call(this, {
date: date,
hasDate: 1,
hasTime: 1
});
};
/*
* 获取指定月份第一天的格式化日期:2000-01-01
* @param date [Date/String]
*/
Date.prototype.firstDayOfMonth = function (date) {
if (date == null) {
date = this;
}
return _firstDayOfMonth.call(this, date);
};
/*
* 获取指定月份最后一天的格式化日期:2000-01-31
* @param date [Date/String]
*/
Date.prototype.lastDayOfMonth = function (date) {
if (date == null) {
date = this;
}
return _lastDayOfMonth.call(this, date);
};
/*
* 获取 n 天前的日期(n 可为负)
*/
Date.prototype.beforeDays = function (n, date) {
if (date == null) {
date = this;
}
return new Date(date.getTime() - n * 1000 * 60 * 60 * 24);
};
/*
* 获取 n 天后的日期(n 可为负)
*/
Date.prototype.afterDays = function (n, date) {
if (date == null) {
date = this;
}
return new Date(date.getTime() + n * 1000 * 60 * 60 * 24);
};
/*
* 获取 n 个月前的日期(n 可为负)
*/
Date.prototype.beforeMonths = function (n, date) {
if (date == null) {
date = this;
}
return new Date(date.setMonth(date.getMonth() - n));
};
/*
* 获取 n 天后的日期(n 可为负)
*/
Date.prototype.afterMonths = function (n, date) {
if (date == null) {
date = this;
}
return new Date(date.setMonth(date.getMonth() + n));
};
/*
* 去空格 - 去除全部空格
*/
String.prototype.trimAll = function () {
return this.replace(/\s/g, '');
};
/*
* 去空格 - 前后空格都去掉
*/
String.prototype.trim = function () {
return this.replace(/(^\s*)|(\s*$)/g, '');
};
/*
* 去空格 - 去前面的空格
*/
String.prototype.trimPre = function () {
return this.replace(/(^\s*)/g, '');
};
/*
* 去空格 - 去后面的空格
*/
String.prototype.trimSuf = function () {
return this.replace(/(\s*$)/g, '');
};
/*
* 处理JSON库
*/
String.prototype.toJSON = function () {
return JSON.parse(this);
};
/*
* 将 $、<、>、"、',与 / 转义成 HTML 字符
*/
String.prototype.encodeHTML = function (onlyEncodeScript) {
var encodeHTMLRules, matchHTML, str;
if (!this) {
return this;
}
encodeHTMLRules = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": ''',
"/": '/'
};
if (onlyEncodeScript) {
matchHTML = /<\/?\s*(script|iframe)[\s\S]*?>/gi;
str = this.replace(matchHTML, function (m) {
var s;
switch (true) {
case /script/i.test(m):
s = 'script';
break;
case /iframe/i.test(m):
s = 'iframe';
break;
default:
s = '';
}
return "" + encodeHTMLRules['<'] + (-1 === m.indexOf('/') ? '' : encodeHTMLRules['/']) + s + encodeHTMLRules['>'];
});
return str.replace(/on[\w]+\s*=/gi, '');
} else {
matchHTML = /&(?!#?\w+;)|<|>|"|'|\//g;
return this.replace(matchHTML, function (m) {
return encodeHTMLRules[m] || m;
});
}
};
/*
* 将 $、<、>、"、',与 / 从 HTML 字符 反转义成正常字符
*/
String.prototype.decodeHTML = String.prototype.decodeHTML || function () {
var decodeHTMLRules, matchHTML;
decodeHTMLRules = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
''': "'",
'/': "/"
};
matchHTML = /&|<|>|"|'|//g;
if (this) {
return this.replace(matchHTML, function (m) {
return decodeHTMLRules[m] || m;
});
} else {
return this;
}
};
/*
* 检测是否是银行卡号
*/
String.prototype.checkLuhn = function () {
var count, i, len, n, num, sum;
num = this.split('');
len = num.length;
sum = 0;
for (i = 0; i < len; i++) {
count = i + 1;
n = +num[len - 1 - i];
if (count % 2 === 0) {
n = n * 2;
if (!(n < 10)) {
n = n - 9;
}
}
sum += n;
}
return sum % 10 === 0;
};
//格式化身份证号
String.prototype.IDCrdFormat = function () {
let str = this.trimAll()
for (let i = 0; i < str.length; i++) {
if (i === 3 || i === 7 || i === 12 || i === 17) {
str = str.slice(0, i) + ' ' + str.slice(i)
}
}
return str
}
// 计算字符长度
String.prototype.getByteLen = function () {
var len = 0;
for (var i = 0; i < this.length; i++) {
var a = this.charAt(i);
if (a.match(/[^\x00-\xff]/ig) != null) {
len += 2;
} else {
len += 1;
}
}
return len;
}
//验证手机号和用户名
String.prototype.phoneReg = function () {
const phoneReg = /^0?(13|14|15|16|17|18|19)[0-9]{9}$/
return phoneReg.test(this)
}
//验证邮箱
String.prototype.emailReg = function () {
const emailReg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/
return emailReg.test(this)
}
//判断密码中文字符
String.prototype.chineseReg = function () {
const chineseReg = /([\u4E00-\u9FA5]|[\uFE30-\uFFA0])+/
return chineseReg.test(this)
}
//特殊字符(含空格)
String.prototype.characterReg = function () {
const nameReg = /^[\u4E00-\u9FA5A-Za-z0-9]+$/
return !nameReg.test(this)
}
/*
* Array: 判断当前 array 中是否存在指定元素
*/
Array.prototype.has = function (obj) {
return this.indexOf(obj) !== -1;
};
/*
* Array: 获取最后一个元素
*/
Array.prototype.last = function () {
return this[this.length - 1];
};
/*
* Array: 去重
* @param bool [Boolean] 是否返回移除的元素array 默认false
*/
Array.prototype.unique = function (bool) {
var hash, j, l, len1, len2, obj, re, result;
if (bool == null) {
bool = false;
}
result = [];
re = [];
hash = {};
if (bool) {
for (j = 0, len1 = this.length; j < len1; j++) {
obj = this[j];
if (hash[obj]) {
re.push(obj);
} else {
result.push(obj);
hash[obj] = true;
}
}
return [result, re];
} else {
for (l = 0, len2 = this.length; l < len2; l++) {
obj = this[l];
if (!hash[obj]) {
result.push(obj);
hash[obj] = true;
}
}
return result;
}
};
/*
* Array: 移除参数中的元素
*/
Array.prototype.remove = function (obj) {
var i;
i = this.indexOf(obj);
if (i === -1) {
return null;
}
return this.splice(i, 1)[0];
};
/*
* 精确小数点位数
* @param count [int] 精确小数点后位数
* @param round [Boolean] 是否四舍五入(默认:yes)
*/
Number.prototype.accurate = function (count, round) {
var i, l, len, num, re, str, temp, txt;
if (round == null) {
round = true;
}
if (this.valueOf() === 0) {
if (count === 0) {
return '0';
}
re = '0.';
for (i = 0; i < count; i++) {
re += '0';
}
return re;
}
temp = Math.pow(10, count);
num = Math[round ? 'round' : 'floor'](this * temp);
num = num / temp;
str = num.toString();
len = count - str.replace(/^\d+\.*/, '').length;
txt = str;
if (len) {
txt += (num % 1 === 0 ? '.' : '');
}
for (i = 0; i < len; i++) {
txt += '0';
}
return txt;
};
/*
* int 随机数
* @param min [int] 随机范围的最小数字
* @param max [int] 随机范围的最大数字
*/
Math.intRange = function (min, max) {
if (min == null) {
min = 0;
}
if (max == null) {
max = 0;
}
return min + Math.round(Math.random() * (max - 1));
};