您的位置:首页 - 文章 - 默认 - 正文

常用的JS工具函数

/** * 文件类型格式化 1图片2视频 */
var DataManipulation = { getFileType: function (vale) { var type = "2"; if (vale.indexOf('image') != -1) { type = "1" } else if (vale.indexOf('video') != -1) { type = "2" } return type; }, hideName: function (value) { var hideStr = value.substring(0, 1) + '**'; return hideStr; }, /** * 性别格式化 */ formartSex: function (value) { var result = '未知'; if (value == '1') { result = "男"; } if (value == '2') { result = "女"; } return result; }, // 数字格式化 makeFriendly: function (num) { if (num >= 100000000) { num = Math.round(num / 10000000) / 10 + '亿' } else if (num >= 10000) { num = Math.round(num / 1000) / 10 + '万' } return num; }, /** * 保留两位小数 */ toFix: function (value) { return value.toFixed(2) }, /** * 保留一位小数 */ toFixOne: function (value) { return value.toFixed(1) }, /** * 四舍五入 */ toFixWhole: function (value) { return value.toFixed(0) }, /** * 分转元 */ toYuan: function (value) { return value / 100 }, /** * 分转元保留两位小数 */ toYuanFix: function (value) { var value = value / 100; return value.toFixed(2) }, /** * 身份证隐藏 */ hideIdCard: function (idCard) { var reg = getRegExp('(^\d{18}$)||(^\d{17}(\d|X||x)$)/') if (reg.test(idCard)) { var buildReg = getRegExp('(^\d{18}$)||(^\d{17}(\d|X|x)$)/') var hideStr = idCard.substring(0, 4) + '**********' + idCard.substring(14); return hideStr; } return idCard; }, /** * 计算年龄 */ getAgeByIdCard: function (idCard) { var len = (identityCard + "").length; if (len == 0) { return 0; } else { if ((len != 15) && (len != 18)) //身份证号码只能为15位或18位其它不合法 { return 0; } } var strBirthday = ""; if (len == 18) //处理18位的身份证号码从号码中得到生日和性别代码 { strBirthday = identityCard.substr(6, 4) + "/" + identityCard.substr(10, 2) + "/" + identityCard.substr(12, 2); } if (len == 15) { strBirthday = "19" + identityCard.substr(6, 2) + "/" + identityCard.substr(8, 2) + "/" + identityCard.substr(10, 2); } //时间字符串里,必须是“/” var birthDate = getDate(strBirthday); var nowDateTime = getDate(); var age = nowDateTime.getFullYear() - birthDate.getFullYear(); //再考虑月、天的因素;.getMonth()获取的是从0开始的,这里进行比较,不需要加1 if (nowDateTime.getMonth() < birthDate.getMonth() || (nowDateTime.getMonth() == birthDate.getMonth() && nowDateTime.getDate() < birthDate.getDate())) { age--; } return age; }, /** * 手机号码隐藏 */ hidePhone: function (phone) { if (phone.length == 11) { var hideStr = phone.substring(0, 3) + '****' + phone.substring(7); return hideStr; } else { return ""; } }, // 隐藏银行卡中间号码 hideBankCard : function(value) { //return `${value.substring(0, 4)} ${"*".repeat(value.length - 8).replace(/(.{4})/g, `$1 `)}${value.length % 4 ? " " : ""}${value.slice(-4)}`; var hideStr = value.substring(0, 4) + '****' + value.substring(value.length-4); return hideStr; }, /** * 毫秒转秒 */ minuteFormat: function (timestamp) { timestamp = parseInt(timestamp); var m = timestamp / 60000; return Math.ceil(m); // m.toFixed(0); }, /** * 时间格式化 */ dateFormat: function (timestamp, format) { var regYear = getRegExp("(y+)", "i"); if (!format) { format = "yyyy-MM-dd hh:mm:ss"; } timestamp = parseInt(timestamp); var realDate = getDate(timestamp); function timeFormat(num) { return num < 10 ? '0' + num : num; } var date = [ ["M+", timeFormat(realDate.getMonth() + 1)], ["d+", timeFormat(realDate.getDate())], ["h+", timeFormat(realDate.getHours())], ["m+", timeFormat(realDate.getMinutes())], ["s+", timeFormat(realDate.getSeconds())], ["q+", Math.floor((realDate.getMonth() + 3) / 3)], ["S+", realDate.getMilliseconds()], ]; var reg1 = regYear.exec(format); if (reg1) { format = format.replace(reg1[1], (realDate.getFullYear() + '').substring(4 - reg1[1].length)); } for (var i = 0; i < date.length; i++) { var k = date[i][0]; var v = date[i][1]; var reg2 = getRegExp("(" + k + ")").exec(format); if (reg2) { format = format.replace(reg2[1], reg2[1].length == 1 ? v : ("00" + v).substring(("" + v).length)); } } return format; }, /** * 仿微信聊天时间格式化 */ dateFormatForWx: function (realDateTimestamp) { function timeFormat(num) { return num < 10 ? '0' + num : num; } realDateTimestamp = parseInt(realDateTimestamp); var nowDate = getDate(); var realDate = getDate(realDateTimestamp); var nowDateTimestamp = Date.parse(getDate()); var todayDateStr = nowDate.getFullYear() + "/" + (timeFormat(nowDate.getMonth() + 1)) + "/" + (timeFormat(nowDate.getDate())) + " 00:00:00"; var tempDateTimestamp = Date.parse(getDate(todayDateStr)); if (realDateTimestamp > tempDateTimestamp) { return timeFormat(realDate.getHours()) + ":" + timeFormat(realDate.getMinutes()) } else { return DataManipulation.dateFormat(realDateTimestamp, 'yyyy年MM月dd日 hh:mm'); } }, /** * 语音时长格式化 */ durationFormert: function (duration) { var formatValue = '0'; duration = parseInt(duration); if (duration > 0) { formatValue = Math.round(duration / 1000); } return formatValue; }, /** * 语音时长 长度padding格式化 */ yypadding: function (duration) { var formatValue = 1; duration = parseInt(duration); if (duration > 0) { formatValue = Math.round(duration / 1000); } if (formatValue >= 10) { formatValue = 10; } if (formatValue < 3) { formatValue = 1; } return formatValue * 20; }, /** * 图片等比例格式化 */ imgeSizeFomFormert: function (width, height) { var tempFormert = ""; if (width && height) { width = parseInt(width); height = parseInt(height); if (width == height) { if (width >= 300) { tempFormert = 'width: 300rpx !important;height: 300rpx !important'; } else { tempFormert = 'width: ' + width + 'rpx !important;height: ' + height + 'rpx !important'; } } else if (height > width) { if (height > 500) { width = 500 / height * width; tempFormert = 'height: 500rpx !important;width: ' + width + 'rpx !important;'; } else { tempFormert = 'width: ' + width + 'rpx !important;height: ' + height + 'rpx !important'; } } else { if (width > 300) { height = 300 / width * height; tempFormert = 'width: 300rpx !important;height: ' + height + 'rpx !important;'; } else { tempFormert = 'width: ' + width + 'rpx !important;height: ' + height + 'rpx !important'; } } } return tempFormert; }, /** * 视频等比例格式化 */ videoSizeFomFormert: function (width, height, rotation) { var tempFormert = ""; if (rotation) { rotation = Math.abs(rotation); } // console.log(rotation) if (rotation == 90 || rotation == 270) { var tempSize = width; width = height; height = tempSize; } if (width > height) { height = Math.floor(300 / width * height) - 2; tempFormert = 'width: 300rpx !important;height: ' + height + 'rpx !important;border-radius: 6rpx;'; } else { height = Math.floor(180 / width * height) - 2; tempFormert = 'width: 180rpx !important;height: ' + height + 'rpx !important;border-radius: 6rpx;'; } return tempFormert; }, /** * 广场 */ gcVideoSizeFomFormert: function (width, height, rotation) { var tempFormert = ""; if (rotation) { rotation = Math.abs(rotation); } // console.log(rotation) if (rotation == 90 || rotation == 270) { var tempSize = width; width = height; height = tempSize; } if (width > height) { height = Math.ceil(710 / width * height); tempFormert = 'width: 710rpx !important;height: ' + height + 'rpx !important;border-radius: 0rpx;'; } else { height = Math.ceil(260 / width * height); tempFormert = 'width: 260rpx !important;height: ' + height + 'rpx !important;border-radius: 0rpx;'; } return tempFormert; }, vdBgMargin: function (width, height, rotation) { var tempFormert = ""; if (rotation) { rotation = Math.abs(rotation); } // console.log(rotation) if (rotation == 90 || rotation == 270) { var tempSize = width; width = height; height = tempSize; } if (width > height) { tempFormert = 'margin-left:0;left:0 !important;;'; } else { tempFormert = 'margin-left:-130rpx !important;;'; } return tempFormert; }, /** * 称呼性别转换 * name 姓名 * sexFlag 0 男 其他女 */ sexFormat: function (name, sexFlag) { var tempFormert = ""; tempFormert = name.substring(0, 1); sexFlag = parseInt(sexFlag); if (sexFlag == 0) { tempFormert = tempFormert + "先生"; } else { tempFormert = tempFormert + "女士"; } return tempFormert; }, /** * 计算时长 */ timeDifference: function (endtime, begintime) { function toDub(n) { return n < 10 ? "0" + n : "" + n; } var date3 = endtime - begintime //计算出相差天数 var days = Math.floor(date3 / (24 * 3600 * 1000)) //计算出小时数 var leave1 = date3 % (24 * 3600 * 1000) //计算天数后剩余的毫秒数 var hours = Math.floor(leave1 / (3600 * 1000)) //计算相差分钟数 var leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数 // var minutes = Math.floor(leave2 / (60 * 1000)) var minutes = Math.floor(date3 / (60 * 1000)) //计算相差秒数 var leave3 = leave2 % (60 * 1000) //计算分钟数后剩余的毫秒数 var seconds = Math.floor(leave3 / 1000) // console.log(" 相差 " + days + "天 " + hours + "小时 " + minutes + " 分钟" + seconds + " 秒") // console.log(toDub(minutes) + ":" + toDub(seconds)) return toDub(minutes) + ":" + toDub(seconds) }, /** * 计算时长(相差多少分钟) */ timeDifferenceSeconds: function (begintime, endtime) { if (!endtime) { endtime = getDate().getTime(); } return Math.floor((endtime - begintime) / 1000 / 60); }, millisecondToDate: function (result) { result = parseInt(result); min = Math.floor((result / 1000 / 60) << 0), sec = Math.floor((result / 1000) % 60); if (min == 0) { min = "00" } else if (min < 10) { min = "0" + min } if (sec == 0) { sec = "00" } else if (sec < 10) { sec = "0" + sec } return min + '分' + sec + '秒'; }, /** * 时间格式化 聊天记录(参考微信) */ dateToWeiXinString: function (dateTimeStamp) { dateTimeStamp = parseInt(dateTimeStamp); var realDate = getDate(dateTimeStamp); var date = { "y": realDate.getFullYear(), //年份 "M": realDate.getMonth() + 1, //月份 "d": realDate.getDate(), //日 "D": realDate.getDay(), "h": realDate.getHours(), //小时 "m": realDate.getMinutes(), //分 "s": realDate.getSeconds(), //秒 "q": Math.floor((realDate.getMonth() + 3) / 3), //季度 "S": realDate.getMilliseconds(), //毫秒 }; var week = ["日", "一", "二", "三", "四", "五", "六"]; var minute = 1000 * 60; var hour = minute * 60; var day = hour * 24; var halfamonth = day * 15; var month = day * 30; var year = day * 365; var now = getDate().getTime(); var diffValue = now - dateTimeStamp; // if (diffValue < 0) { // return '数据出错'; // } var dataNow = getDate(); var yearC = dataNow.getFullYear() - realDate.getFullYear(); var today = getDate(dataNow.getFullYear(), dataNow.getMonth(), dataNow.getDate()); var yesterday = getDate(dataNow.getFullYear(), dataNow.getMonth(), dataNow.getDate() - 1); var beforeYesterday = getDate(dataNow.getFullYear(), dataNow.getMonth(), dataNow.getDate() - 2); var hourC = realDate.getHours(); var hourCN = ""; var oneDayTime = 1000 * 60 * 60 * 24; var old_count = parseInt(dateTimeStamp / oneDayTime); var now_other = parseInt(now / oneDayTime); var isOneWeek = parseInt((old_count + 4) / 7) == parseInt((now_other + 4) / 7); if (hourC == 12) { hourCN = "中午"; } else { var hourTitle = ["凌晨", "早上", "下午", "晚上"]; hourCN = hourTitle[parseInt(hourC / 6)]; } if (realDate.getTime() >= today.getTime()) { result = hourCN + (date.h > 9 ? date.h : '0' + date.h) + ":" + (date.m > 9 ? date.m : '0' + date.m); } else if (realDate.getTime() > yesterday.getTime()) { result = '昨天' + " " + hourCN + (date.h > 9 ? date.h : '0' + date.h) + ":" + (date.m > 9 ? date.m : '0' + date.m); } else if (isOneWeek) { result = "星期" + week[date.D] + " " + hourCN + (date.h > 9 ? date.h : '0' + date.h) + ":" + (date.m > 9 ? date.m : '0' + date.m); } else if (yearC == 0) { result = date.M + "月" + date.d + "日" + " " + hourCN + DataManipulation.dateFormat(dateTimeStamp, 'hh:mm'); } else { result = date.y + "年" + date.M + "月" + date.d + "日" + " " + hourCN + (date.h > 9 ? date.h : '0' + date.h) + ":" + (date.m > 9 ? date.m : '0' + date.m); } return result; }, /** * 帖子发表时间格式化 */ getDateDiff: function (dateTimeStamp) { var minute = 1000 * 60; var hour = minute * 60; var day = hour * 24; var halfamonth = day * 15; var month = day * 30; var year = day * 365; var now = getDate().getTime(); var diffValue = now - dateTimeStamp; if (diffValue < 0) { //非法操作 return '刚刚'; } var yearC = diffValue / year; var monthC = diffValue / month; var weekC = diffValue / (7 * day); var dayC = diffValue / day; var hourC = diffValue / hour; var minC = diffValue / minute; if (yearC >= 1) { result = parseInt(yearC) + '年以前'; } else if (monthC >= 1) { result = parseInt(monthC) + '个月前'; } else if (weekC >= 1) { result = parseInt(weekC) + '星期前'; } else if (dayC >= 1) { result = parseInt(dayC) + '天前'; } else if (hourC >= 1) { result = parseInt(hourC) + '小时前'; } else if (minC >= 5) { result = parseInt(minC) + '分钟前'; } else { result = '刚刚'; } return result; }, // 是否包含字符串 // includes: function(st, aa) { // return st.indexOf(aa) // }
};
module.exports = { hideBankCard:DataManipulation.hideBankCard, toFixWhole: DataManipulation.toFixWhole, toFix: DataManipulation.toFix, toYuan: DataManipulation.toYuan, toYuanFix: DataManipulation.toYuanFix, hideIdCard: DataManipulation.hideIdCard, hidePhone: DataManipulation.hidePhone, dateFormat: DataManipulation.dateFormat, dateFormatForWx: DataManipulation.dateFormatForWx, durationFormert: DataManipulation.durationFormert, yypadding: DataManipulation.yypadding, imgeSizeFomFormert: DataManipulation.imgeSizeFomFormert, sexFormat: DataManipulation.sexFormat, getAgeByIdCard: DataManipulation.getAgeByIdCard, hideName: DataManipulation.hideName, minuteFormat: DataManipulation.minuteFormat, toFixOne: DataManipulation.toFixOne, timeDifference: DataManipulation.timeDifference, millisecondToDate: DataManipulation.millisecondToDate, formartSex: DataManipulation.formartSex, makeFriendly: DataManipulation.makeFriendly, videoSizeFomFormert: DataManipulation.videoSizeFomFormert, getFileType: DataManipulation.getFileType, dateToWeiXinString: DataManipulation.dateToWeiXinString, getDateDiff: DataManipulation.getDateDiff, timeDifferenceSeconds: DataManipulation.timeDifferenceSeconds, gcVideoSizeFomFormert: DataManipulation.gcVideoSizeFomFormert, vdBgMargin: DataManipulation.vdBgMargin // includes: DataManipulation.includes
}
本文原创,作者:西决,其版权均为品创网络所有。如需转载,请注明出处:https://www.sxpcwlkj.com/js-util/

发表评论