tools.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. // 小数运算精度处理 4位小数运算后结果保留2位小数
  2. export const getOperationalPrecision = (num1, num2) => {
  3. const val = ((num1 * 10000) * (num2 * 10000) / 100000000).toFixed(2) || 0
  4. return val != 0 ? val : 0
  5. }
  6. // 加粗替换字符串中的金额
  7. export const boldAmounts = (text) => {
  8. let regex = /(\d+\.?\d*)元/g;
  9. let regex5 = /(\d+\.?\d*)件/g;
  10. let regex6 = /(\d+\.?\d*)个/g;
  11. let regex1 = /再满(\d+\.?\d*)元,可享受优惠/g;
  12. let regex4 = /再满(\d+\.?\d*)件产品可享受优惠/g;
  13. let regex2 = /(\d+\.?\d*)(/g
  14. let regex3 = /选择(\d+\.?\d*)个/g
  15. let rext = text.replace(regex1, '<b>再满$1元,可享受优惠</b>');
  16. rext = rext.replace(regex4, '<b>再满$1件产品可享受优惠</b>');
  17. rext = rext.replace(regex, '<span>$1</span>元');
  18. rext = rext.replace(regex5, '<span>$1</span>件');
  19. rext = rext.replace(regex6, '<span>$1</span>个');
  20. rext = rext.replace(regex2, '<span>$1</span>(');
  21. rext = rext.replace(regex3, '选择<span>$1</span>个');
  22. return rext;
  23. }
  24. // 金额转大写
  25. export const dealBigMoney = (n) => {
  26. if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(n)) { return '数据非法' }
  27. let unit = '千百拾亿千百拾万千百拾元角分'; let str = ''
  28. n += '00'
  29. const p = n.indexOf('.')
  30. if (p >= 0) {
  31. n = n.substring(0, p) + n.substr(p + 1, 2)
  32. unit = unit.substr(unit.length - n.length)
  33. }
  34. for (var i = 0; i < n.length; i++) { str += '零壹贰叁肆伍陆柒捌玖'.charAt(n.charAt(i)) + unit.charAt(i) }
  35. return str.replace(/零(千|百|拾|角)/g, '零').replace(/(零)+/g, '零').replace(/零(万|亿|元)/g, '$1').replace(/(亿)万|壹(拾)/g, '$1$2').replace(/^元零?|零分/g, '').replace(/元$/g, '元整')
  36. }
  37. export const forEach = (arr, fn) => {
  38. if (!arr.length || !fn) return
  39. let i = -1
  40. const len = arr.length
  41. while (++i < len) {
  42. const item = arr[i]
  43. fn(item, i, arr)
  44. }
  45. }
  46. /**
  47. * @param {Array} arr1
  48. * @param {Array} arr2
  49. * @description 得到两个数组的交集, 两个数组的元素为数值或字符串
  50. */
  51. export const getIntersection = (arr1, arr2) => {
  52. const len = Math.min(arr1.length, arr2.length)
  53. let i = -1
  54. const res = []
  55. while (++i < len) {
  56. const item = arr2[i]
  57. if (arr1.indexOf(item) > -1) res.push(item)
  58. }
  59. return res
  60. }
  61. /**
  62. * @param {Array} arr1
  63. * @param {Array} arr2
  64. * @description 得到两个数组的并集, 两个数组的元素为数值或字符串
  65. */
  66. export const getUnion = (arr1, arr2) => {
  67. return Array.from(new Set([...arr1, ...arr2]))
  68. }
  69. /**
  70. * @param {Array} target 目标数组
  71. * @param {Array} arr 需要查询的数组
  72. * @description 判断要查询的数组是否至少有一个元素包含在目标数组中
  73. */
  74. export const hasOneOf = (targetarr, arr) => {
  75. if (!targetarr) return true
  76. if (!arr) return true
  77. return targetarr.some(_ => arr.indexOf(_) > -1)
  78. }
  79. /**
  80. * @param {String|Number} value 要验证的字符串或数值
  81. * @param {*} validList 用来验证的列表
  82. */
  83. export function oneOf (value, validList) {
  84. for (let i = 0; i < validList.length; i++) {
  85. if (value === validList[i]) {
  86. return true
  87. }
  88. }
  89. return false
  90. }
  91. /**
  92. * @param {Number} timeStamp 判断时间戳格式是否是毫秒
  93. * @returns {Boolean}
  94. */
  95. const isMillisecond = timeStamp => {
  96. const timeStr = String(timeStamp)
  97. return timeStr.length > 10
  98. }
  99. /**
  100. * @param {Number} timeStamp 传入的时间戳
  101. * @param {Number} currentTime 当前时间时间戳
  102. * @returns {Boolean} 传入的时间戳是否早于当前时间戳
  103. */
  104. const isEarly = (timeStamp, currentTime) => {
  105. return timeStamp < currentTime
  106. }
  107. /**
  108. * @param {Number} num 数值
  109. * @returns {String} 处理后的字符串
  110. * @description 如果传入的数值小于10,即位数只有1位,则在前面补充0
  111. */
  112. const getHandledValue = num => {
  113. return num < 10 ? '0' + num : num
  114. }
  115. /**
  116. * @param {Number} timeStamp 传入的时间戳
  117. * @param {Number} startType 要返回的时间字符串的格式类型,传入'year'则返回年开头的完整时间
  118. */
  119. const getDate = (timeStamp, startType) => {
  120. const d = new Date(timeStamp * 1000)
  121. const year = d.getFullYear()
  122. const month = getHandledValue(d.getMonth() + 1)
  123. const date = getHandledValue(d.getDate())
  124. const hours = getHandledValue(d.getHours())
  125. const minutes = getHandledValue(d.getMinutes())
  126. const second = getHandledValue(d.getSeconds())
  127. let resStr = ''
  128. if (startType === 'year') resStr = year + '-' + month + '-' + date + ' ' + hours + ':' + minutes + ':' + second
  129. else resStr = month + '-' + date + ' ' + hours + ':' + minutes
  130. return resStr
  131. }
  132. /**
  133. * @param {Number} timeStamp 传入的时间戳
  134. * @param {Number} fmt 格式化字符串
  135. */
  136. export const formtDate = (timeStamp, fmt) => {
  137. const d = new Date(timeStamp)
  138. var o = {
  139. 'M+': d.getMonth() + 1, // 月份
  140. 'd+': d.getDate(), // 日
  141. 'h+': d.getHours(), // 小时
  142. 'm+': d.getMinutes(), // 分
  143. 's+': d.getSeconds(), // 秒
  144. 'q+': Math.floor((d.getMonth() + 3) / 3), // 季度
  145. 'S': d.getMilliseconds() // 毫秒
  146. }
  147. if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (d.getFullYear() + '').substr(4 - RegExp.$1.length))
  148. for (var k in o) { if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length))) }
  149. return fmt
  150. }
  151. // 获取三个月后的时间戳
  152. export const getThreeMonthsAfter = (dtstr) => {
  153. var s = dtstr.split('-')
  154. var yy = parseInt(s[0])
  155. var mm = parseInt(s[1])
  156. var dd = parseInt(s[2])
  157. var dt = new Date(yy, mm + 2, dd)
  158. return dt.valueOf()
  159. }
  160. /**
  161. * @param {String|Number} timeStamp 时间戳
  162. * @returns {String} 相对时间字符串
  163. */
  164. export const getRelativeTime = timeStamp => {
  165. // 判断当前传入的时间戳是秒格式还是毫秒
  166. const IS_MILLISECOND = isMillisecond(timeStamp)
  167. // 如果是毫秒格式则转为秒格式
  168. if (IS_MILLISECOND) Math.floor(timeStamp /= 1000)
  169. // 传入的时间戳可以是数值或字符串类型,这里统一转为数值类型
  170. timeStamp = Number(timeStamp)
  171. // 获取当前时间时间戳
  172. const currentTime = Math.floor(Date.parse(new Date()) / 1000)
  173. // 判断传入时间戳是否早于当前时间戳
  174. const IS_EARLY = isEarly(timeStamp, currentTime)
  175. // 获取两个时间戳差值
  176. let diff = currentTime - timeStamp
  177. // 如果IS_EARLY为false则差值取反
  178. if (!IS_EARLY) diff = -diff
  179. let resStr = ''
  180. const dirStr = IS_EARLY ? '前' : '后'
  181. // 少于等于59秒
  182. if (diff <= 59) resStr = diff + '秒' + dirStr
  183. // 多于59秒,少于等于59分钟59秒
  184. else if (diff > 59 && diff <= 3599) resStr = Math.floor(diff / 60) + '分钟' + dirStr
  185. // 多于59分钟59秒,少于等于23小时59分钟59秒
  186. else if (diff > 3599 && diff <= 86399) resStr = Math.floor(diff / 3600) + '小时' + dirStr
  187. // 多于23小时59分钟59秒,少于等于29天59分钟59秒
  188. else if (diff > 86399 && diff <= 2623859) resStr = Math.floor(diff / 86400) + '天' + dirStr
  189. // 多于29天59分钟59秒,少于364天23小时59分钟59秒,且传入的时间戳早于当前
  190. else if (diff > 2623859 && diff <= 31567859 && IS_EARLY) resStr = getDate(timeStamp)
  191. else resStr = getDate(timeStamp, 'year')
  192. return resStr
  193. }
  194. // 日期格式化
  195. export const formatSubmitDate = (val, type) => {
  196. if (val == null || val == '' || val == undefined) {
  197. return ''
  198. } else {
  199. const _date = new Date(val)
  200. const _year = _date.getFullYear()
  201. const _montn = (_date.getMonth() + 1) < 10 ? '0' + (_date.getMonth() + 1) : (_date.getMonth() + 1)
  202. const _day = _date.getDate() < 10 ? '0' + _date.getDate() : _date.getDate()
  203. const _hour = _date.getHours() < 10 ? '0' + _date.getHours() : _date.getHours()
  204. const _minutes = _date.getMinutes() < 10 ? '0' + _date.getMinutes() : _date.getMinutes()
  205. const _seconds = _date.getSeconds() < 10 ? '0' + _date.getSeconds() : _date.getSeconds()
  206. if (type == 'minutes') return _year + '-' + _montn + '-' + _day + ' ' + _hour + ':' + _minutes
  207. else if (type == 'seconds') return _year + '-' + _montn + '-' + _day + ' ' + _hour + ':' + _minutes + ':' + _seconds
  208. else return _year + '-' + _montn + '-' + _day
  209. }
  210. }
  211. // 正则验证车牌,验证通过返回true,不通过返回false
  212. export const isLicensePlate = function (str) {
  213. return /^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$/.test(str)
  214. }
  215. // 车牌可输入字符
  216. export const isCarNumber = function (str) {
  217. let _value = str + ''
  218. _value = _value.replace(/[^\w\.挂学警港澳使领]/ig, '')
  219. return _value
  220. }
  221. // 小数点后两位
  222. export const numberToFixed = function (val, num) {
  223. let _value = val + ''
  224. _value = _value.replace(/[^\d.]/g, '')// 清楚数字和.以外的字数
  225. _value = _value.replace(/^\./g, '')
  226. _value = _value.replace(/\.{2,}/g, '')// 保留第一个,清楚多余的
  227. if (num == 1)_value = _value.replace(/^(\-)*(\d+)\.(\d).*$/, '$1$2.$3')
  228. else if (num == 3)_value = _value.replace(/^(\-)*(\d+)\.(\d\d\d).*$/, '$1$2.$3')
  229. else if (num == 4)_value = _value.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/, '$1$2.$3')
  230. else if (num == 5)_value = _value.replace(/^(\-)*(\d+)\.(\d\d\d\d\d).*$/, '$1$2.$3')
  231. else if (num == 0)_value = _value.replace(/^(\-)*(\d+)\.*$/, '$1$2')
  232. else _value = _value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
  233. return _value
  234. }
  235. export const toFixedDecimal = function (num, decimal) {
  236. let newNum = null
  237. const patrn = /[\u4E00-\u9FA5]|[\uFE30-\uFFA0]/gi
  238. if (!patrn.exec(num)) {
  239. newNum = parseFloat(num).toFixed(decimal)
  240. } else {
  241. newNum = num
  242. }
  243. return newNum
  244. }
  245. // 保留decimal位小数(不四舍五入) num 数值,decimal要保留的小数位数
  246. export const formatDecimal = function (num, decimal) {
  247. num = num.toString()
  248. const index = num.indexOf('.')
  249. if (index !== -1) {
  250. num = num.substring(0, decimal + index + 1)
  251. } else {
  252. num = num.substring(0)
  253. }
  254. return parseFloat(num).toFixed(decimal)
  255. }
  256. // 处理数字千位分隔符 num 数值,decimal要保留的小数位数
  257. export const toThousands = (num, decimal) => {
  258. if (num == undefined) {
  259. return '--'
  260. }
  261. num = formatDecimal(num, decimal || decimal == 0 ? decimal : 2)
  262. return '' + num.toString().replace(/\d+/, function (n) { // 先提取整数部分
  263. return n.replace(/(\d)(?=(\d{3})+$)/g, function ($1) {
  264. return $1 + ''
  265. })
  266. })
  267. }
  268. // 只能输入数字
  269. export const justNumber = function (val) {
  270. let _value = val + ''
  271. _value = _value.replace(/\D/g, '')
  272. return _value
  273. }
  274. /**
  275. * @returns {String} 当前浏览器名称
  276. */
  277. export const getExplorer = () => {
  278. const ua = window.navigator.userAgent
  279. const isExplorer = (exp) => {
  280. return ua.indexOf(exp) > -1
  281. }
  282. if (isExplorer('MSIE')) return 'IE'
  283. else if (isExplorer('Firefox')) return 'Firefox'
  284. else if (isExplorer('Chrome')) return 'Chrome'
  285. else if (isExplorer('Opera')) return 'Opera'
  286. else if (isExplorer('Safari')) return 'Safari'
  287. }
  288. /**
  289. * @description 绑定事件 on(element, event, handler)
  290. */
  291. export const on = (function () {
  292. if (document.addEventListener) {
  293. return function (element, event, handler) {
  294. if (element && event && handler) {
  295. element.addEventListener(event, handler, false)
  296. }
  297. }
  298. } else {
  299. return function (element, event, handler) {
  300. if (element && event && handler) {
  301. element.attachEvent('on' + event, handler)
  302. }
  303. }
  304. }
  305. })()
  306. /**
  307. * @description 解绑事件 off(element, event, handler)
  308. */
  309. export const off = (function () {
  310. if (document.removeEventListener) {
  311. return function (element, event, handler) {
  312. if (element && event) {
  313. element.removeEventListener(event, handler, false)
  314. }
  315. }
  316. } else {
  317. return function (element, event, handler) {
  318. if (element && event) {
  319. element.detachEvent('on' + event, handler)
  320. }
  321. }
  322. }
  323. })()
  324. /**
  325. * 判断一个对象是否存在key,如果传入第二个参数key,则是判断这个obj对象是否存在key这个属性
  326. * 如果没有传入key这个参数,则判断obj对象是否有键值对
  327. */
  328. export const hasKey = (obj, key) => {
  329. if (key) return key in obj
  330. else {
  331. const keysArr = Object.keys(obj)
  332. return keysArr.length
  333. }
  334. }
  335. /**
  336. * @param {*} obj1 对象
  337. * @param {*} obj2 对象
  338. * @description 判断两个对象是否相等,这两个对象的值只能是数字或字符串
  339. */
  340. export const objEqual = (obj1, obj2) => {
  341. const keysArr1 = Object.keys(obj1)
  342. const keysArr2 = Object.keys(obj2)
  343. if (keysArr1.length !== keysArr2.length) return false
  344. else if (keysArr1.length === 0 && keysArr2.length === 0) return true
  345. /* eslint-disable-next-line */
  346. else return !keysArr1.some(key => obj1[key] != obj2[key])
  347. }
  348. /*
  349. * @param {*} id 数字
  350. * @param {*} list 数组
  351. * @description 根据id从数组列表中删除某一项
  352. */
  353. export const removeListById = (id, list) => {
  354. list.splice(list.findIndex(item => item.id === id), 1)
  355. }
  356. /**
  357. * @param {*} obj1 对象
  358. * @param {*} obj2 对象
  359. * @description 遍历赋值
  360. */
  361. export const objExtend = (obj1, obj2) => {
  362. for (var a in obj1) {
  363. obj2[a] = obj1[a]
  364. }
  365. return obj2
  366. }
  367. /**
  368. * @param {*} obj 对象
  369. * @description 浅拷贝
  370. */
  371. export const cloneObj = (obj) => {
  372. const ret = {}
  373. for (var a in obj) {
  374. ret[a] = obj[a]
  375. }
  376. return ret
  377. }
  378. /**
  379. * 校验身份证号合法性
  380. */
  381. export const checkIdNumberValid = (tex) => {
  382. // var tip = '输入的身份证号有误,请检查后重新输入!'
  383. let num = tex
  384. num = num.toUpperCase()
  385. const len = num.length
  386. let re
  387. if (len == 0) return true
  388. // 身份证号码为15位或者18位,15位时全为数字,18位前17位为数字,最后一位是校验位,可能为数字或字符X。
  389. if (!(/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(num))) {
  390. return false
  391. }
  392. // 验证前两位地区是否有效
  393. const aCity = { 11: '北京',
  394. 12: '天津',
  395. 13: '河北',
  396. 14: '山西',
  397. 15: '内蒙古',
  398. 21: '辽宁',
  399. 22: '吉林',
  400. 23: '黑龙江',
  401. 31: '上海',
  402. 32: '江苏',
  403. 33: '浙江',
  404. 34: '安徽',
  405. 35: '福建',
  406. 36: '江西',
  407. 37: '山东',
  408. 41: '河南',
  409. 42: '湖北',
  410. 43: '湖南',
  411. 44: '广东',
  412. 45: '广西',
  413. 46: '海南',
  414. 50: '重庆',
  415. 51: '四川',
  416. 52: '贵州',
  417. 53: '云南',
  418. 54: '西藏',
  419. 61: '陕西',
  420. 62: '甘肃',
  421. 63: '青海',
  422. 64: '宁夏',
  423. 65: '新疆',
  424. 71: '台湾',
  425. 81: '香港',
  426. 82: '澳门',
  427. 91: '国外' }
  428. if (aCity[parseInt(num.substr(0, 2))] == null) {
  429. return false
  430. }
  431. // 当身份证为15位时的验证出生日期。
  432. if (len == 15) {
  433. re = new RegExp(/^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/)
  434. const arrSplit = num.match(re)
  435. // 检查生日日期是否正确
  436. const dtmBirth = new Date('19' + arrSplit[2] + '/' + arrSplit[3] + '/' + arrSplit[4])
  437. const bGoodDay = (dtmBirth.getYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[3])) && (dtmBirth.getDate() == Number(arrSplit[4]))
  438. if (!bGoodDay) {
  439. return false
  440. }
  441. }
  442. // 当身份证号为18位时,校验出生日期和校验位。
  443. if (len == 18) {
  444. re = new RegExp(/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/)
  445. const arrSplit = num.match(re)
  446. // 检查生日日期是否正确
  447. const dtmBirth = new Date(arrSplit[2] + '/' + arrSplit[3] + '/' + arrSplit[4])
  448. const bGoodDay = (dtmBirth.getFullYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[3])) && (dtmBirth.getDate() == Number(arrSplit[4]))
  449. if (!bGoodDay) {
  450. return false
  451. } else {
  452. // 检验18位身份证的校验码是否正确。
  453. // 校验位按照ISO 7064:1983.MOD 11-2的规定生成,X可以认为是数字10。
  454. let valnum
  455. const arrInt = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
  456. const arrCh = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
  457. let nTemp = 0
  458. let i
  459. for (i = 0; i < 17; i++) {
  460. nTemp += num.substr(i, 1) * arrInt[i]
  461. }
  462. valnum = arrCh[nTemp % 11]
  463. if (valnum != num.substr(17, 1)) {
  464. return false
  465. }
  466. }
  467. }
  468. return true
  469. }
  470. // 清除空格和特殊字符
  471. export const removeEmptyStr = function(str){
  472. if(str){
  473. var strs=str.toString()
  474. strs= strs.replace(/^\s+|\s+$/gm,'');
  475. strs=strs.replace(/[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~!@#¥%……&*()——\-+={}|《》?:“”【】、;‘',。、]/im,'');
  476. return strs;
  477. }
  478. return '';
  479. }
  480. // 移动数组项
  481. export const moveElement = function (arr, fromIndex, toIndex) {
  482. const element = arr.splice(fromIndex, 1)[0];
  483. arr.splice(toIndex, 0, element);
  484. return arr;
  485. }
  486. // 校验特殊字符
  487. export const validateSpecialCharacter = function(rule, value, callback){
  488. var regex = /[!@#$%^&*(),.?":{}|<>]/;
  489. if(regex.test(value)){
  490. return callback(new Error('不能输入特殊字符'));
  491. }else{
  492. callback()
  493. }
  494. }