1. 千分位格式化数字
formatNum(num) { //千分位格式化数字
return num && num.toString().replace(/(?=(?!^)(\d{3})+$)/g, ',')
}
2. 字符串替换所有空格
变量.replace(/\s+/g, '')
var str = ' A B C D EF ';
console.log(str.replace(/\s/g, '#')); // ##A#B##C###D#EF#
console.log(str.replace(/\s+/g, '#')); // #A#B#C#D#EF#
3. 获取中英文字符串的字节数
let string = '我是王小文aaa';
function strlen(str) {
var len = 0;
for (var i = 0; i < str.length; i++) {
var c = str.charCodeAt(i);
// 英文单字节加1 ,汉字加2
if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
len++;
} else {
len += 2;
}
}
return len;
}
console.log(strlen(string));
4. 计时器 --> 通过【setInterval】累计毫秒数
(function () {
start();
})()
let ms = 0;
timeStr = '';
function start() {
// 要记得清楚定时器,否则会有多个定时器叠加!
// clearInterval(this.timeInterval);
let timeInterval = setInterval(timer.bind(this), 1000);
}
// 计时器
function timer() {
ms = ms + 1000;
timeStr = this.formatTime(ms);
let divHtml = document.getElementsByTagName('div')[0];
divHtml.innerHTML = timeStr;
}
// 格式化时间
function formatTime(date) {
const formatDate = new Date(date);
const hour = formatDate.getHours() - 8;
const minute = formatDate.getMinutes();
const second = formatDate.getSeconds();
const timeArray = [hour, minute, second].map(this.formatNumber);
// 小时没有,暂不显示
if (timeArray[0] === '00') {
timeArray.splice(0, 1);
}
return timeArray.join(':');
}
function formatNumber(n) {
n = n.toString();
return n[1] ? n : '0' + n;
}
5. 格式化日期格式
// 传入毫秒数作为参数,转化为date对象来处理日期和时间(Date 对象基于1970年1月1日(世界标准时间)起的毫秒数。)
let date = new Date(36525);
function formatTime(date) {
var year = date.getFullYear()
var month = date.getMonth() + 1
var day = date.getDate()
var hour = date.getHours()
var minute = date.getMinutes()
var second = date.getSeconds()
return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
function formatNumber(n) {
n = n.toString()
return n[1] ? n : '0' + n
}
6. 根据身份证获取出生日期
getBirthdayFromIdCard(idCard) {
let birthday = '';
if (idCard != null && idCard !== '') {
if (idCard.length === 15) {
birthday = '19' + idCard.substr(6, 6);
} else if (idCard.length === 18) {
birthday = idCard.substr(6, 8);
}
const year = birthday.substr(0, 4);
const month = birthday.substr(4, 2);
const day = birthday.substr(6, 2);
return year + '-' + month + '-' + day;
}
}
网友评论