用正则实现时间格式化、获取URL地址的参数信息、大数字千分符处理

 ~function(){
        <!-- 
            formatTime:时间字符串的格式化处理
                @params
                    template:[string] 我们最后期望获取日期格式的模板
                    模板规则:{0}->{1~5}->月日时分秒
                @return
                    [string]格式化后的时间字符串
        -->
        function formatTime(template = "{0}年{1}月{2}日 {3}时{4}分{5}秒"){
            // 1、首先获取时间字符串中的年月日等信息
            let timeAry = this.match(/\d+/g)
            return template.replace(/\{(\d+)\}/g,(content,$1)=>{
                // content:当前本次大正则匹配的信息   $1:本次小分组单独匹配的信息
                // 以$1的值作为索引,到timeAry中找到对应的时间(如果没有则用"00"补)
                let time = timeAry[$1] || "00"
                return time.length < 2 ? "0" + time : time
            })
        }
        <!-- 扩展到内置类String.prototype上 -->
        ['formatTime'].forEach(item => {
            String.prototype[item] = eval(item)
        })
    }()
    let time = '2020-11-9 11:24:55'
    console.log(this.formatTime())
~function(){
        <!-- 
            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
        }
        <!-- 扩展到内置类String.prototype上 -->
        ['queryURLParams'].forEach(item => {
            String.prototype[item] = eval(item)
        })
    }()
    let url = 'http://www.aabbcc.com/?a=1&b=2#c'
    console.log(url.queryURLParams())
~function(){
        <!-- 
            millimeter:实现大数字的千分符处理
            @params
            @return
                [string]千分符后的字符串
         -->
        function millimeter(){
            return this.replace(/\d{1,3}(?=(\d{3})+$)/g,content => content + ',')
        }
        <!-- 扩展到内置类String.prototype上 -->
        ['millimeter'].forEach(item => {
            String.prototype[item] = eval(item)
        })
    }()

    let num = '12345678'  // => '12,345,678' 千分符
    把字符串倒过来加
    num = num.split('').reverse().join('')
    for(let i = 2;i < num.length - 1; i += 4){
        let prev = num.substring(0,i+1),
            next = num.substring(i+1)
        num = prev + ',' + next
    }
    num = num.split('').reverse().join('')
    console.log(num)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值