1. 格式化字符串,字符串左边补0
function leftZero(str, len){
str = ''+str;
return str.length >= len ? str : new Array(len - str.length + 1).join('0') + str;
}
2. 格式化价格,添加逗号分隔
function formatCommas(val){
if(isNaN(val)){
return '-';
}
val = (val+"").split(".");
return val[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g,"$1,")+(val.length>1?"."+val[1]:"");
}
3. 格式化日期
const formatDate = (fmt, date) => {
var o = {
"M+" : date.getMonth()+1,
"d+" : date.getDate(),
"h+" : date.getHours(),
"m+" : date.getMinutes(),
"s+" : date.getSeconds(),
"q+" : Math.floor((date.getMonth()+3)/3),
"S" : date.getMilliseconds()
};
if(/(y+)/.test(fmt))
fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
for(var k in o)
if(new RegExp("("+ k +")").test(fmt))
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
return fmt;
}
const addDate = (interval, number, date) => {
switch (interval) {
case "y": {
date.setFullYear(date.getFullYear() + number);
return date;
break;
}
case "q": {
date.setMonth(date.getMonth() + number * 3);
return date;
break;
}
case "m": {
date.setMonth(date.getMonth() + number);
return date;
break;
}
case "w": {
date.setDate(date.getDate() + number * 7);
return date;
break;
}
case "d": {
date.setDate(date.getDate() + number);
return date;
break;
}
case "h": {
date.setHours(date.getHours() + number);
return date;
break;
}
case "m": {
date.setMinutes(date.getMinutes() + number);
return date;
break;
}
case "s": {
date.setSeconds(date.getSeconds() + number);
return date;
break;
}
default: {
date.setDate(d.getDate() + number);
return date;
break;
}
}
}
4. 获取URL参数
function getQueryParam(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
if (r != null) return unescape(r[2]); return null;
}