news 2026/6/10 16:08:16

好用的js工具类

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
好用的js工具类

格式化相关

//***********************金额格式化************************* /** * 将大额数字转换为万、亿等,并向下保留2位小数 * @param value 数字 * @param unit 转换单位 * @returns {{}}bigNumberTransform(19999999,'单')输出1,999.99万单 */ export function bigNumberTransform(value,unit) { let newVal = Math.abs(value) let param = {} let k = 10000, sizes = ['元', '万', '亿', '万亿'], i if (newVal < k) { param.value = newVal param.unit = unit } else { i = Math.floor(Math.log(newVal) / Math.log(k)) param.value = Math.floor((newVal / Math.pow(k, i)) * 100) / 100 param.unit = sizes[i]+unit } if (value < 0) { param.value = '-' + toThousands(param.value) } else { param.value = toThousands(param.value) } return param } /** * 将数字金额转换为大写中文金额 * @param n * @returns {string} */ export function digitUppercase (n) { const fraction = ['角', '分']; const digit = [ '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖' ]; const unit = [ ['元', '万', '亿'], ['', '拾', '佰', '仟'] ]; n = Math.abs(n); let s = ''; for (let i = 0; i < fraction.length; i++) { s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, ''); } s = s || '整'; n = Math.floor(n); for (let i = 0; i < unit[0].length && n > 0; i++) { let p = ''; for (let j = 0; j < unit[1].length && n > 0; j++) { p = digit[n % 10] + unit[1][j] + p; n = Math.floor(n / 10); } s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s; } return s.replace(/(零.)*零元/, '元') .replace(/(零.)+/g, '零') .replace(/^整$/, '零元整'); }; /** * 金额转换,分转换为元 * @param num * @returns {string} */ export function fenToYuan(num) { if (typeof num === 'undefined') return '0.00' const parsedNumber = typeof num === 'string' ? parseFloat(num) : num return (parsedNumber / 100.0).toFixed(2) } /** * 金额转换,元转换为分 * @param num * @returns {number} */ export function yuanToFen(num) { if (typeof num === 'undefined') return 0 const parsedNumber = typeof num === 'string' ? parseFloat(num) : num return Math.round(parsedNumber * 100) } /** * 数字每三位增加一个逗号 * @param num * @returns {number|string}toThousands(10000)输出10,000 */ export function toThousands(num) { if (num) { return num.toString().replace(/\d+/, function(n) { // 先提取整数部分 return n.replace(/(\d)(?=(\d{3})+$)/g, function($1) { return $1 + ',' }) }) } else { return 0 } } //***********************其他格式化************************* /** * 将undefined,null等转化为"" * @param str * @returns {*|string} */ export function praseStrEmpty(str) { if (!str || str === 'undefined' || str === 'null') { return '' } return str } /** * 手机号中间4位变**** * @param tel * @returns {string} */ export function telFormat(tel) { return String(tel).slice(0, 3) + "****" + String(tel).slice(7); } /** * 字符串脱敏函数:保留首尾指定长度的字符,中间用 * 代替 * @param {string} str - 需要脱敏的原始字符串 * @param {number} headLen - 需要保留的前缀长度(默认 3) * @param {number} tailLen - 需要保留的后缀长度(默认 4) * @param {string} maskChar - 替换的掩码字符(默认 *) * @returns {string} 脱敏后的字符串 */ export function desensitizeString(str, headLen = 3, tailLen = 4, maskChar = '*') { // 1. 基础校验:如果传入的不是字符串,或者为空,直接返回空字符串 if (!str || typeof str !== 'string') { return ''; } // 2. 长度校验:如果字符串总长度小于等于需要保留的首尾长度之和,则不进行脱敏,直接返回原字符串 if (str.length <= headLen + tailLen) { return str; } // 3. 提取前缀和后缀 const head = str.slice(0, headLen); const tail = str.slice(-tailLen); // 4. 计算中间需要替换的字符数量,并生成掩码 const middleLen = str.length - headLen - tailLen; const maskedPart = maskChar.repeat(middleLen); // 5. 拼接并返回结果 return head + maskedPart + tail; } /** * 数字转化为中文数字 * @param value * @returns {string} */ export function intToChinese(value) { const str = String(value); const len = str.length-1; const idxs = ['','十','百','千','万','十','百','千','亿','十','百','千','万','十','百','千','亿']; const num = ['零','一','二','三','四','五','六','七','八','九']; return str.replace(/([1-9]|0+)/g, ( $, $1, idx, full) => { let pos = 0; if($1[0] !== '0'){ pos = len-idx; if(idx == 0 && $1[0] == 1 && idxs[len-idx] == '十'){ return idxs[len-idx]; } return num[$1[0]] + idxs[len-idx]; } else { let left = len - idx; let right = len - idx + $1.length; if(Math.floor(right / 4) - Math.floor(left / 4) > 0){ pos = left - left % 4; } if( pos ){ return idxs[pos] + num[$1[0]]; } else if( idx + $1.length >= len ){ return ''; }else { return num[$1[0]] } } }); } /** * 根据身份证获取性别 * @param idCard * @returns {string} */ export function getSexByIdCard(idCard) { // 1. 基础校验:确保传入的是非空字符串 if (!idCard || typeof idCard !== 'string') { return ''; } let genderCode = ''; // 2. 根据身份证长度提取性别码 if (idCard.length === 15) { // 15位身份证:性别码在最后一位(第15位) genderCode = idCard.slice(-1); } else if (idCard.length === 18) { // 18位身份证:性别码在倒数第二位(第17位) genderCode = idCard.slice(-2, -1); } else { // 长度不符合规范 return ''; } // 3. 判断奇偶性并返回性别 // 奇数为男,偶数为女 if (parseInt(genderCode, 10) % 2 === 1) { return '男'; } else if (parseInt(genderCode, 10) % 2 === 0) { return '女'; } return ''; } /** * 根据身份证获取年龄 * @param idCard * @returns {number|number} */ export function getAgeByIdCard(idCard) { // 1. 基础校验:确保传入的是非空字符串 if (typeof idCard !== 'string' || idCard.length === 0) { return 0; } const len = idCard.length; let birthYear = 0, birthMonth = 0, birthDay = 0; // 2. 根据身份证长度提取出生年月日 if (len === 18) { birthYear = parseInt(idCard.substring(6, 10), 10); birthMonth = parseInt(idCard.substring(10, 12), 10) - 1; // JS中月份从0开始 birthDay = parseInt(idCard.substring(12, 14), 10); } else if (len === 15) { birthYear = parseInt('19' + idCard.substring(6, 8), 10); birthMonth = parseInt(idCard.substring(8, 10), 10) - 1; birthDay = parseInt(idCard.substring(10, 12), 10); } else { // 长度不符合规范,直接返回0 return 0; } // 3. 使用安全的 Date 构造函数创建日期对象 const birthDate = new Date(birthYear, birthMonth, birthDay); // 校验日期是否合法(防止出现如 1990-02-30 这种无效日期) if (isNaN(birthDate.getTime())) { return 0; } // 4. 计算周岁年龄 const now = new Date(); let age = now.getFullYear() - birthDate.getFullYear(); // 如果今年的生日还没到,年龄减 1 const isBirthdayPassed = now.getMonth() > birthDate.getMonth() || (now.getMonth() === birthDate.getMonth() && now.getDate() >= birthDate.getDate()); if (!isBirthdayPassed) { age--; } return age >= 0 ? age : 0; }

校验相关

//正整数校验 export function validatePositiveInteger (num) { return !/^(0|\+?[1-9][0-9]*)$/.test(num) } //最多两位小数 export function validateMoney (money) { return !/^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/.test(money) } // 不能只有空格 export function validateAllBlank (value) { return value.trim().length === 0 } // 不能包含空格 export function validateSpace (value) { return !/^\S*$/.test(value) } // 只能包含英文字母 export function validateEng (value) { return /[^a-zA-Z]/.test(value) } //身份证号码校验 export function checkIdCard (idCard) { var regexp = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/ return regexp.test(idCard) } //邮箱校验 export function isEmail (value) { return /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value); } //手机号校验 export function checkPhoneNumber (phoneNumber) { return /^[1]([3-9])[0-9]{9}$/.test(phoneNumber.replace(/\s+/g, '')) } /** * 密码校验:用于校验8-16位由数字、字母或符号组成,并且至少包含2种及以上字符 */ export function validatePassword (password) { const regex = /^(?![0-9]+$)(?![a-zA-Z]+$)(?![^0-9a-zA-Z]+$)[\w!@#$%^&*()\-+=<>?.,;:'"{}[\]|\\\/]{8,16}$/; return regex.test(password); }

时间相关:使用moment或者dayjs

momentjs,dayjs常用方法-CSDN博客

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/6/10 16:07:13

Bugly SDK架构设计解析:理解腾讯Bugly的技术实现原理

Bugly SDK架构设计解析&#xff1a;理解腾讯Bugly的技术实现原理 【免费下载链接】Bugly-Android-Demo Bugly Android SDK 使用例子 项目地址: https://gitcode.com/gh_mirrors/bu/Bugly-Android-Demo 腾讯Bugly是一款专业的移动应用质量监控平台&#xff0c;其Android …

作者头像 李华
网站建设 2026/6/10 16:05:17

Progenitor生成CLI工具:从OpenAPI规范到命令行交互的完整流程

Progenitor生成CLI工具&#xff1a;从OpenAPI规范到命令行交互的完整流程 【免费下载链接】progenitor An OpenAPI client generator 项目地址: https://gitcode.com/gh_mirrors/pr/progenitor Progenitor是一款强大的OpenAPI客户端生成工具&#xff0c;能够帮助开发者快…

作者头像 李华
网站建设 2026/6/10 16:04:23

技术架构革新:重新定义时间序列预测的未来

技术架构革新&#xff1a;重新定义时间序列预测的未来 【免费下载链接】timesfm TimesFM (Time Series Foundation Model) is a pretrained time-series foundation model developed by Google Research for time-series forecasting. 项目地址: https://gitcode.com/GitHub_…

作者头像 李华