時間字元傳格式化
let time = '2020-3-30 23:2:00'
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}秒'));
console.log(time.formatTime('{0}年{1}月{2}日'));
console.log(time.formatTime('{3}時{4}分{5}秒'));
複製程式碼
url引數處理
let url = 'https://mbd.baidu.com?context=%7B%&type=0&p_from=1#sss';
function queryURLParams(url) {
let askIndex = url.indexOf('?'),
wellIndex = url.lastIndexOf('#'),
askText = '',
wellText = '',
obj = {};
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);
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);
複製程式碼