js时间字符串格式化以及url参数处理

2,930 阅读1分钟

时间字符传格式化

let time = '2020-3-30 23:2:00'
/* 
 *formatTime:时间字符串格式化处理
 *  @params
 *      template:格式化模板字符串,即我们期望获取的日期格式的模板
 *      {0}->年 {1-5}->月日时分秒
 *  @return
 *      处理好的日期格式字符串
 */
function formatTime(template = '{0}年{1}月{2}日 {3}时{4}分{5}秒') {
    let arr = this.match(/\d+/g);
    let reg = /\{(\d)\}/g;
    template = template.replace(reg, ($1, $2) => {
        return arr[$2].length<2 ? '0'+ arr[$2] : arr[$2];
    });
    return template;
}
String.prototype.formatTime = formatTime;
console.log(time.formatTime('{0}年{1}月{2}日 {3}时{4}分{5}秒')); //=>2020年03月30日 23时02分00秒
console.log(time.formatTime('{0}年{1}月{2}日')); //=>2020年03月30日
console.log(time.formatTime('{3}时{4}分{5}秒')); //=>23时02分00秒

url参数处理

let url = 'https://mbd.baidu.com?context=%7B%&type=0&p_from=1#sss';
/* 
 * queryURLParams:获取url参数
 *   @params
 *      url:被处理的url字符串
 *   @return
 *      普通对象(该对象中哈希值,以及等号左右组成字符组成的键值对)
 */
function queryURLParams(url) {
    let askIndex = url.indexOf('?'),
        wellIndex = url.lastIndexOf('#'),
        askText = '',
        wellText = '',
        obj = {};
    // 判断是否存在#,如果存在截取#后面的值,如果不存在让wellIndex等于length
    wellIndex !== -1 ? wellText = url.substring(wellIndex + 1) : wellIndex = url.length;
    wellText ? obj.HASH = wellText : null;
    // 判断问号是否存在
    askIndex !== -1 ? askText = url.substring(askIndex + 1, wellIndex) : null;
    if (askText) {
        let arr = askText.split('&');
        arr.forEach(item => {
            let newArr = item.split('=');
            obj[newArr[0]] = newArr[1];
        });
    }
    return obj;
}
let obj = queryURLParams(url);
console.log(obj); //=>{HASH: "sss", context: "%7B%", type: "0", p_from: "1"}

// 基于正则处理url参数
function queryURLParams(url) {
    let obj = {};
    url.replace(/([^#&?=]+)=([^#&?=]+)/g, (_, $1, $2) => obj[$1] = $2);
    url.replace(/#([^#&?=]+)/g, (_, $1) => obj['HASH'] = $1);
    return obj;
}
let obj = queryURLParams(url);
console.log(obj); //=>{HASH: "sss", context: "%7B%", type: "0", p_from: "1"}