~function(){
/*
*formatTime时间格式化处理
* @params
* templete:[string]我们最后期望获取日期格式的模板
* 模板规则:{0} 年 {2-5}->月日时分秒
* @return
* [string]格式化后的时间字符串
*/
function formatTime(templete="{0}年{1}月{2}日 {3}时{4}分{5}秒"){
//首先获取时间字符串中的年月日等信息
let timeAry = this.match(/d+/g); //['2020','4','12','11','29','30']
return templete.replace(/{(d+)}/g,(...[content,$1])=>{
//content:当前本次大正则匹配的信息,$1:本次小组单独匹配的信息
//以$1的值作为索引,到timeAry中找到对应的时间(如果没有则用'00'补)
let time = timeAry[$1] || '00';
return time.length < 2 ? time = '0'+time : time;
})
}
/*
*queryURLParams:获取URL地址问号后面的参数信息(可能也包含hash值)
* @params
* @return
* [object]把所有问号参数信息以键值对的方式储存起来并且返回对象
*/
function queryURLParams(){
let obj = {};
this.replace(/([^?&=#]+)=([^?&=#]+)/g,(...[,$1,$2])=> obj[$1]=$2)
this.replace(/#([^?&=#]+)/g,(...[,$1])=>obj['HASH']=$1)
return obj;
}
/*
* milliMeter:千分符
* @return
* [string]千分符后的字符串
*/
function milliMeter(){
return this.replace(/d{1,3}(?=(d{3})+$)/g,(content)=> content+',')
}
/*扩展到内置类Sring.prototype上*/
['formatTime','queryURLParams','milliMeter'].forEach(item=>{
String.prototype[item]=eval(item);
})
}()
let time = '2020-4-12 11:29:30';
console.log(time.formatTime());//2020年04月12日 11时29分30秒
console.log(time.formatTime('{0}年{1}月{2}日'));//2020年04月12日
time = '2010/4/22';
console.log(time.formatTime());//2010年04月22日 00时00分00秒
console.log(time.formatTime('{1}-{2}')); //04-22
let url = 'http://www.baidu.com?id=2&name=lili#value'
console.log(url.queryURLParams()); //{id: "2", name: "lili", HASH: "value"}
let num = '78478427213333';
console.log(num.milliMeter()); //78,478,427,213,333