概述
js日期格式化,连字符转驼峰等通用函数记录
1. 基本通用函数
通用函数js很多实现都在lodash里面有实现,如 throttle(节流函数) 和 debounce(防抖函数)
2.一些其他的函数记录
2.1 连字符转驼峰 和 驼峰转连字符
// 连字符转驼峰
String.prototype.hyphenToHump = function () {
return this.replace(/-(w)/g, (...args) => {
return args[1].toUpperCase()
})
}
// 驼峰转连字符
String.prototype.humpToHyphen = function () {
return this.replace(/([A-Z])/g, '-$1').toLowerCase()
}
2.2 获取URL上面的参数方法
/**
* @param name {String}
* @return {String}
*/
export function queryURL (name) {
let reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`, 'i')
let r = window.location.search.substr(1).match(reg)
if (r != null) return decodeURI(r[2])
return null
}
2.3日期格式化
// 日期格式化
Date.prototype.format = function (format) {
const o = {
'M+': this.getMonth() + 1,
'd+': this.getDate(),
'h+': this.getHours(),
'H+': this.getHours(),
'm+': this.getMinutes(),
's+': this.getSeconds(),
'q+': Math.floor((this.getMonth() + 3) / 3),
S: this.getMilliseconds(),
}
if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1, `${this.getFullYear()}`.substr(4 - RegExp.$1.length))
}
for (let k in o) {
if (new RegExp(`(${k})`).test(format)) {
format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : (`00${o[k]}`).substr(`${o[k]}`.length))
}
}
return format
}
2.4 千分位加逗号
// 千分位加逗号函数
export default function toThousands(num) {
var num = (num || 0).toString(), result = '';
while (num.length > 3) {
result = ',' + num.slice(-3) + result;
num = num.slice(0, num.length - 3);
}
if (num) { result = num + result; }
return result;
}
2.5 字符串长度(英文占一个字符,中文两个字符)
// 字符串长度(英文占1个字符,中文汉字占2个字符)
String.prototype.gblen = function() {
var len = 0;
for (var i=0; i<this.length; i++) {
if (this.charCodeAt(i)>127 || this.charCodeAt(i)==94) {
len += 2;
} else {
len ++;
}
}
return len;
}
thanks.
最后
以上就是欣喜手机为你收集整理的js日期格式化,连字符转驼峰等通用函数记录js日期格式化,连字符转驼峰等通用函数记录的全部内容,希望文章能够帮你解决js日期格式化,连字符转驼峰等通用函数记录js日期格式化,连字符转驼峰等通用函数记录所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复