常用工具函数
1. 将整数部分逢三一断
参数.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
2. 金额只保留小数点后三位
参数.toString().substring(0,value.lastIndexOf('.')+4)
3. 获取地址栏参数
function getQueryString(name) { if (window.location.href.indexOf("?") != window.location.href.lastIndexOf("?")) var urls = window.location.href.replace(/\?/g, "&").replace(/^.*?&/, "") else var urls = window.location.href.replace(/^.*\?/, ""); var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); var r = ("?" + urls).substr(1).match(reg); if (r != null) return unescape(r[2]); return null; }
4. 获得输入框中字符长度
function getStringLength(val) { var str = new String(val) var bytesCount = 0 for (var i = 0 ,n = str.length; i < n; i++) { var c = str.charCodeAt(i) if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) { bytesCount += 1 } else { bytesCount += 2 } } return bytesCount }
5. 正则 —— 汉字、字母、数字
参数.match(/^[A-Za-z0-9\u4e00-\u9fa5]+$/gi)
6. 时间格式转换
/** * 时间格式转换 YYYY-MM-DD * @param date 时间对象 * @param type 返回时间格式 */ const timeFormat = (dateObj, type) => { if (!(dateObj instanceof Date)) { throw new Error('参数dateObj不是Date实例') } let year = dateObj.getFullYear() let month = ('00' + (dateObj.getMonth() + 1)).slice(-2) let date = ('00' + dateObj.getDate()).slice(-2) let hours = ('00' + dateObj.getHours()).slice(-2) let minutes = ('00' + dateObj.getMinutes()).slice(-2) let seconds = ('00' + dateObj.getSeconds()).slice(-2) let timeString = '' let _type = type || 'YYYY-MM-DD' switch (_type) { case 'YYYY-MM-DD HH:MM:SS': timeString = `${year}-${month}-${date} ${hours}:${minutes}:${seconds}` break case 'YYYY-MM-DD HH:MM': timeString = `${year}-${month}-${date} ${hours}:${minutes}` break case 'YYYY-MM-DD': timeString = `${year}-${month}-${date}` break case 'MM-DD HH:MM': timeString = `${month}-${date} ${hours}:${minutes}` break case 'HH:MM:SS': timeString = `${hours}:${minutes}:${seconds}` break case 'HH:MM': timeString = `${hours}:${minutes}` break default: break } return timeString }

浙公网安备 33010602011771号