提供一些日常開發中,實用得代碼片段。歡迎大家補充!
1、手機號隱藏中間4位
//手機號脫敏 function mobile(data) { return data.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2'); }
2、證件號脫敏,包括但不限於身份證
//身份證脫敏 -- 1 function idCard(data) { return data.replace(/(\d{4})\d*([0-9xX]{4})/, "$1******$2"); } //身份證脫敏 -- 2 function idCard(data) { if(data.toString().length == 18) { return data.slice(0,2) + '****************' + data.slice(16,18) } else if(data.toString().length == 15) { return data.slice(0,2) + '***********' + data.slice(13,15) } } //證件脫敏,data->數據,beforeLen->前置位數,afterLen->后置位數 function newIdCard(data, beforeLen, afterLen) { let dataLenth = data.length - beforeLen - afterLen let middleStr = '' for (let i = 0; i < dataLenth; i++) { middleStr += '*' } return data.slice(0, 2) + middleStr + data.substring(data.length - afterLen) }
3、金額處理,經常會遇到數字相乘或相除得問題,但結果往往不是我們想要得,例如12.32 * 7 結果是86.24000000000001;
為了避免此種情況得發生,以萬元為單位提供一種方法。詳細解釋請查看https://www.cnblogs.com/weiqt/articles/2642393.html
//金額 export function money(num){ return num >= 10000 ? parseFloat(num) * 10000/100000000+'萬' : num }
4、根據需要返回不同類型得日期
//格式化時間 export function dateFormat(time,fmt){ return fnDateFormat(time,fmt) } export default function(time,fmt){ var fmt = fmt || 'yyyy-MM-dd HH:mm:ss'; var time = time ? new Date(time) : new Date(); var o = { "M+" : time.getMonth()+1, //月份 "d+" : time.getDate(), //日 "H+" : time.getHours(), //小時 "m+" : time.getMinutes(), //分 "s+" : time.getSeconds(), //秒 "S" : time.getMilliseconds() //毫秒 }; if(/(y+)/.test(fmt)) fmt=fmt.replace(RegExp.$1, (time.getFullYear()+"").substr(4 - RegExp.$1.length)); 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))); return fmt; }
5、通過身份證獲取年齡、性別、生日
//通過身份證獲取年齡 & 生日 const idCardBirthday = function(data){ //獲取出生年月日 var year = data.substring(6,10); var month = data.substring(10,12); var day = data.substring(12,14); return `${year}-${month}-${day}` } //通過身份證獲取性別 const idCardGender = function(data){ //1 男 2 女 return parseInt(data.slice(-2, -1)) % 2 == 1 ? 1 : 2; } const birthdayAge = function(str, type) { var type = type || 'year'; //補零 let zeroize = function(value) { if (value < 10) { value = '0' + value } return value } var birthDay = new Date(str) var yearBirth = birthDay.getFullYear(); var monthBirth = birthDay.getMonth() + 1; var dayBirth = birthDay.getDate(); var myDate = new Date(); var monthNow = myDate.getMonth() + 1; var dayNow = myDate.getDate(); var age = myDate.getFullYear() - yearBirth; if (monthNow < monthBirth || (monthNow == monthBirth && dayNow < dayBirth)) { age--; } return age } export default { idCardBirthday , idCardGender, birthdayAge }
6、常用正則表達式
//手機號 const mobile = /^[1]+\d{10}$/; //身份證 //const idCard = /(^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$) | (^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/; //18位 & 15位 const idCard = /^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/ //護照 const passport = /^[0-9A-Z]{7,11}$/ //姓名 不包含特殊字符 //const name = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>《》/?~!@#¥……&*()——|{}【】‘;:”“'。,、?+0-9]"); const name = /(^([a-zA-Z]+\s)*[a-zA-Z]+$)|(^[\u4E00-\u9FA5]+$)/; //字母 const letter = /^[A-Za-z]+$/ //網址 const domain = /(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/; //郵箱 const email = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/ //納稅號 const corporationTax = /^[0-9A-Z]{15,20}$/
7、文件下載,針對PDF
/** * 文件鏈接轉文件流下載--主要針對pdf 解決谷歌瀏覽器a標簽下載pdf直接打開的問題 * @param url :文件鏈接 * @param fileName :文件名; * @param type :文件類型; */ export function fileLinkToStreamDownload(url, fileName, type) { let reg = /^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\/])+$/; if (!reg.test(url)) { throw new Error("傳入參數不合法,不是標准的文件鏈接"); } else { let xhr = new XMLHttpRequest(); xhr.open('get', url, true); xhr.setRequestHeader('Content-Type', `application/${type}`); xhr.responseType = "blob"; xhr.onload = function () { if (this.status == 200) { //接受二進制文件流 var blob = this.response; downloadExportFile(blob, fileName, type) } } xhr.send(); } } /** *下載導出文件 * @param blob :返回數據的blob對象或鏈接 * @param tagFileName :下載后文件名標記 * @param fileType :文件類 word(docx) excel(xlsx) ppt等 */ function downloadExportFile(blob, tagFileName, fileType) { let downloadElement = document.createElement('a'); let href = blob; if (typeof blob == 'string') { downloadElement.target = '_blank'; } else { href = window.URL.createObjectURL(blob); //創建下載的鏈接 } downloadElement.href = href; downloadElement.download = tagFileName + '.' + fileType; //下載后文件名 document.body.appendChild(downloadElement); downloadElement.click(); //點擊下載 document.body.removeChild(downloadElement); //下載完成移除元素 if (typeof blob != 'string') { window.URL.revokeObjectURL(href); //釋放掉blob對象 } }