js日期格式化,連字元轉駝峰等通用函式記錄
阿新 • • 發佈:2019-01-07
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.