/**
* 为String对象添加format方法
* 这是个占位符替换方法
* "您好,今天是{0}年{1}月{2}日".format("2017","01","20")=="您好,今天是2017年01月20日"
*/
String.prototype.format=function(){
if(arguments.length==0) return this;
for(var s=this, i=0; i<arguments.length; i++)
s=s.replace(new RegExp("\\{"+i+"\\}","g"), arguments[i]);
return s;
};
/**
* 为Date对象添加format方法
* new Date().format("yyyy-MM-dd hh:mm:ss:SSS");年月日时分秒毫秒
*/
Date.prototype.format = function (fmt) { //author: meizz
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"h+": this.getHours(), //小时
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
}
/**
* url解析
* 获取协议,地址,端口,路径,请求参数,锚点
*/
function parseUrl(url) {
var matcher = url.match(/^(?:(\w+):\/\/)?([^#:\/?]+)(?::(\d+))?(?:(\/[^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/);
if (matcher == null) {
throw new Error("not match");
}
var result = {
data: names = ['url', 'protocol', 'host', 'port', 'path', 'arg', 'anchor'],
protocol: 'http',
port: 80
};
for (var i = 0; i < result.data.length; i++) {
if (matcher[i] || matcher[i] === 0) {
result[result.data[i]] = matcher[i];
}
}
if (result['arg']) {
result['argobj'] = parseArg(result['arg']);
}
return result;
}
/**
* url参数解析
* 形如:itemId=123&order=2
* 返回键值对
*/
function parseArg(arg) {
var result = {};
var temp = arg.split('&');
for (var i = 0; i < temp.length; i++) {
var kv = temp[i].split('=');
result[kv[0]] = kv[1];
}
return result;
};
var url = "https://www.test.com:8080/main/tag/index.html?itemId=123&order=2#main"
console.info(parseUrl(url));
/**
* 字符串多层分割(递归)
* str:待分割的字符串
* separators:分隔符数组
* formatObj:是否将最后一层解析为键值对对象
* 流程:先将字符串用分隔符数组里的第一个分隔符分割,再将分割得到的结果依次使用分隔符数组的第二个分隔符分割...直至最后一个分隔符
*/
function deepSplit(str, separators, formatObj) {
var arr = [];
var temp1 = str.split(separators[0]);
var subSeparator = separators.slice(1);
if (subSeparator.length == 0)
return formatObj ? {[temp1[0]]: temp1[1]} : temp1;
for (var j = 0; j < temp1.length; j++)
arr.push(deepSplit(temp1[j], subSeparator, formatObj))
return arr;
}
var content = `a 1
aa 11
ab 12
ac 13
b 2
bb 22
bc 23
bd 24`
console.info(deepSplit(content, ['\n\n', '\n', ' ']));
console.info(deepSplit(content, ['\n\n', '\n', ' '], true));
Javascript扩展方法
最新推荐文章于 2023-10-27 14:07:47 发布