格式化时间字符串
String.prototype.formatTime = function formatTime(template) {
// 1.根据操作的时间字符串获取年月日小时分钟秒等信息
let arr = this.match(/\d+/g).map(item => {
return item.length < 2 ? '0' + item : item;
});
// 2.解析格式化的模板,找到对应的时间,替换模板中的内容
template = template || '{0}年{1}月{2}日 {3}时{4}分{5}秒';
return template.replace(/\{(\d+)\}/g, (_, group) => {
return arr[group] || "00";
});
};
处理URL参数
(proto => {
function queryURLParams() {
let obj = {};
this.replace(/([^?=&#]+)=([^?=&#]+)/g, (_, key, value) => obj[key] = value);
this.replace(/#([^?=&#]+)/g, (_, hash) => obj['HASH'] = hash);
return obj;
}
proto.queryURLParams = queryURLParams;
})(String.prototype);
console.log('http://www.xxxxxxx.cn/?lx=1&name=JS&from=baidu#video'.queryURLParams());
// 输出一个对象
实现千分符
String.prototype.millimeter = function millimeter() {
return this.replace(/\d{1,3}(?=(\d{3})+$)/g, value => {
return value + ',';
});
};
console.log('2132141241'.millimeter()) // 2,132,141,241
检测数据类型
function toType(obj) {
let class2type = {};
["Boolean", "Number", "String", "Function", "Array", "Date", "RegExp", "Object", "Error", "Symbol"].forEach(
item => {
class2type["[object " + item + "]"] = item.toLowerCase();
});
if (obj == null) return obj + "";
return typeof obj === "object" || typeof obj === "function" ?
class2type[class2type.toString.call(obj)] || "object" :
typeof obj;
}
let obj = function () {};
console.log(toType(obj))