JavaScript工具函数大全

开发 前端
本文介绍了JavaScript的工具函数是怎样运用的,我们一起来看看吧。

 

如果文章和笔记能带您一丝帮助或者启发,请不要吝啬你的赞和收藏,你的肯定是我前进的最大动力😁

为元素添加on方法 

  1. ElementElement.prototype.on = Element.prototype.addEventListener;  
  2. NodeList.prototype.on = function (event, fn) {、  
  3.     []['forEach'].call(this, function (el) { 
  4.          el.on(event, fn);  
  5.     });  
  6.     return this;  
  7. }; 

为元素添加trigger方法 

  1. Element.prototype.trigger = function(type, data) {  
  2.   var event = document.createEvent("HTMLEvents");  
  3.   event.initEvent(type, true, true);  
  4.   event.data = data || {};  
  5.   event.eventName = type 
  6.   event.target = this 
  7.   this.dispatchEvent(event);  
  8.   return this;  
  9. };  
  10. NodeList.prototype.trigger = function(event) {  
  11.   []["forEach"].call(this, function(el) {  
  12.     el["trigger"](event);  
  13.   });  
  14.   return this;  
  15. }; 

转义html标签 

  1. function HtmlEncode(text) {  
  2.   return text  
  3.     .replace(/&/g, "&")  
  4.     .replace(/\"/g, '"')  
  5.     .replace(/</g, "<")  
  6.     .replace(/>/g, ">");  

HTML标签转义 

  1. // HTML 标签转义  
  2. // @param {Array.<DOMString>} templateData 字符串类型的tokens  
  3. // @param {...} ..vals 表达式占位符的运算结果tokens  
  4. //  
  5. function SaferHTML(templateData) {  
  6.   var s = templateData[0];  
  7.   for (var i = 1; i < arguments.length; i++) {  
  8.     var arg = String(arguments[i]);  
  9.     // Escape special characters in the substitution.  
  10.     s += arg  
  11.       .replace(/&/g, "&amp;")  
  12.       .replace(/</g, "&lt;")  
  13.       .replace(/>/g, "&gt;");  
  14.     // Don't escape special characters in the template.  
  15.     s += templateData[i];  
  16.   }  
  17.   return s;  
  18.  
  19. // 调用  
  20. var html = SaferHTML`<p>这是关于字符串模板的介绍</p>`; 

跨浏览器绑定事件 

  1. function addEventSamp(obj, evt, fn) {  
  2.   if (!oTarget) {  
  3.     return;  
  4.   }  
  5.   if (obj.addEventListener) {  
  6.     obj.addEventListener(evt, fn, false);  
  7.   } else if (obj.attachEvent) {  
  8.     obj.attachEvent("on" + evt, fn);  
  9.   } else {  
  10.     oTarget["on" + sEvtType] = fn;  
  11.   }  

加入收藏夹 

  1. function addFavorite(sURL, sTitle) {  
  2.   try {  
  3.     window.external.addFavorite(sURL, sTitle);  
  4.   } catch (e) {  
  5.     try {  
  6.       window.sidebar.addPanel(sTitle, sURL, "");  
  7.     } catch (e) {  
  8.       alert("加入收藏失败,请使用Ctrl+D进行添加");  
  9.     }  
  10.   }  

提取页面代码中所有网址 

  1. var aa = document.documentElement.outerHTML 
  2.   .match(  
  3.     /(url\(|src=|href=)[\"\']*([^\"\'\(\)\<\>\[\] ]+)[\"\'\)]*|(http:\/\/[\w\-\.]+[^\"\'\(\)\<\>\[\] ]+)/gi  
  4.   )  
  5.   .join("\r\n")  
  6.   .replace(/^(src=|href=|url\()[\"\']*|[\"\'\>\) ]*$/gim, "");  
  7. alert(aa); 

动态加载脚本文件 

  1. function appendscript(src, text, reload, charset) {  
  2.   var id = hash(src + text);  
  3.   if (!reload && in_array(id, evalscripts)) return;  
  4.   if (reload && $(id)) {  
  5.     $(id).parentNode.removeChild($(id));  
  6.   }  
  7.   evalscripts.push(id);  
  8.   var scriptNode = document.createElement("script");  
  9.   scriptNode.type = "text/javascript" 
  10.   scriptNode.id = id;  
  11.   scriptNode.charset = charset  
  12.     ? charset  
  13.     : BROWSER.firefox  
  14.     ? document.characterSet  
  15.     : document.charset;  
  16.   try {  
  17.     if (src) {  
  18.       scriptNode.src = src;  
  19.       scriptNode.onloadDone = false 
  20.       scriptNode.onload = function() {  
  21.         scriptNode.onloadDone = true 
  22.         JSLOADED[src] = 1;  
  23.       };  
  24.       scriptNode.onreadystatechange = function() {  
  25.         if (  
  26.           (scriptNode.readyState == "loaded" ||  
  27.             scriptNode.readyState == "complete") &&  
  28.           !scriptNode.onloadDone  
  29.         ) {  
  30.           scriptNode.onloadDone = true 
  31.           JSLOADED[src] = 1;  
  32.         }  
  33.       };  
  34.     } else if (text) {  
  35.       scriptNode.text = text;  
  36.     }  
  37.     document.getElementsByTagName("head")[0].appendChild(scriptNode);  
  38.   } catch (e) {}  

返回顶部的通用方法 

  1. function backTop(btnId) {  
  2.   var btn = document.getElementById(btnId);  
  3.   var d = document.documentElement;  
  4.   var b = document.body;  
  5.   window.onscroll = set
  6.    btn.style.display = "none" 
  7.   btn.onclick = function() {  
  8.     btn.style.display = "none" 
  9.     window.onscroll = null 
  10.     this.timer = setInterval(function() {  
  11.       d.scrollTop -Math.ceil((d.scrollTop + b.scrollTop) * 0.1);  
  12.       b.scrollTop -Math.ceil((d.scrollTop + b.scrollTop) * 0.1);  
  13.       if (d.scrollTop + b.scrollTop == 0)  
  14.         clearInterval(btn.timer, (window.onscroll = set));  
  15.     }, 10);  
  16.   };  
  17.   function set() {  
  18.     btn.style.display = d.scrollTop + b.scrollTop > 100 ? "block" : "none";  
  19.   }  
  20.  
  21. backTop("goTop"); 

实现base64解码 

  1. function base64_decode(data) {  
  2.   var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" 
  3.   var o1,  
  4.     o2,  
  5.     o3,  
  6.     h1,  
  7.     h2,  
  8.     h3,  
  9.     h4,  
  10.     bits,  
  11.     i = 0 
  12.     ac = 0 
  13.     dec = "" 
  14.     tmp_arr = [];  
  15.   if (!data) {  
  16.     return data;  
  17.   }  
  18.   data += "";  
  19.   do {  
  20.     h1 = b64.indexOf(data.charAt(i++));  
  21.     h2 = b64.indexOf(data.charAt(i++));  
  22.     h3 = b64.indexOf(data.charAt(i++));  
  23.     h4 = b64.indexOf(data.charAt(i++));  
  24.     bits = (h1 << 18) | (h2 << 12) | (h3 << 6) | h4;  
  25.     o1 = (bits >> 16) & 0xff;  
  26.     o2 = (bits >> 8) & 0xff;  
  27.     o3 = bits & 0xff;  
  28.     if (h3 == 64) {  
  29.       tmp_arr[ac++] = String.fromCharCode(o1);  
  30.     } else if (h4 == 64) {  
  31.       tmp_arr[ac++] = String.fromCharCode(o1, o2);  
  32.     } else {  
  33.       tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);  
  34.     }  
  35.   } while (i < data.length);  
  36.   dec = tmp_arr.join("");  
  37.   dec = utf8_decode(dec);  
  38.   return dec;  

确认是否是键盘有效输入值 

  1. function checkKey(iKey) {  
  2.   if (iKey == 32 || iKey == 229) {  
  3.     return true;  
  4.   } /*空格和异常*/  
  5.   if (iKey > 47 && iKey < 58) {  
  6.     return true;  
  7.   } /*数字*/ 
  8.    if (iKey > 64 && iKey < 91) {  
  9.     return true;  
  10.   } /*字母*/  
  11.   if (iKey > 95 && iKey < 108) {  
  12.     return true;  
  13.   } /*数字键盘1*/  
  14.   if (iKey > 108 && iKey < 112) {  
  15.     return true;  
  16.   } /*数字键盘2*/  
  17.   if (iKey > 185 && iKey < 193) {  
  18.     return true;  
  19.   } /*符号1*/  
  20.   if (iKey > 218 && iKey < 223) {  
  21.     return true;  
  22.   } /*符号2*/  
  23.   return false;  

全角半角转换 

  1. //iCase: 0全到半,1半到全,其他不转化  
  2. function chgCase(sStr, iCase) {  
  3.   if (  
  4.     typeof sStr != "string" ||  
  5.     sStr.length <= 0 ||  
  6.     !(iCase === 0 || iCase == 1)  
  7.   ) {  
  8.     return sStr;  
  9.   }  
  10.   var i,  
  11.     oRs = [],  
  12.     iCode;  
  13.   if (iCase) {  
  14.     /*半->全*/  
  15.     for (i = 0; i < sStr.length; i += 1) {  
  16.       iCode = sStr.charCodeAt(i);  
  17.       if (iCode == 32) {  
  18.         iCode = 12288 
  19.       } else if (iCode < 127) {  
  20.         iCode += 65248;  
  21.       }  
  22.       oRs.push(String.fromCharCode(iCode));  
  23.     }  
  24.   } else {  
  25.     /*全->半*/  
  26.     for (i = 0; i < sStr.length; i += 1) {  
  27.       iCode = sStr.charCodeAt(i);  
  28.       if (iCode == 12288) {  
  29.         iCode = 32 
  30.       } else if (iCode > 65280 && iCode < 65375) {  
  31.         iCode -65248 
  32.       }  
  33.       oRs.push(String.fromCharCode(iCode));  
  34.     }  
  35.   }  
  36.   return oRs.join("");  

版本对比 

  1. function compareVersion(v1, v2) {  
  2.   v1v1 = v1.split(".");  
  3.   v2v2 = v2.split("."); 
  4.   var len = Math.max(v1.length, v2.length);  
  5.   while (v1.length < len) {  
  6.     v1.push("0");  
  7.   }  
  8.   while (v2.length < len) {  
  9.     v2.push("0");  
  10.   }  
  11.   for (var i = 0; i < len; i++) {  
  12.     var num1 = parseInt(v1[i]);  
  13.     var num2 = parseInt(v2[i]);  
  14.     if (num1 > num2) {  
  15.       return 1;  
  16.     } else if (num1 < num2) {  
  17.       return -1;  
  18.     }  
  19.   }  
  20.   return 0;  

压缩CSS样式代码 

  1. function compressCss(s) {  
  2.   //压缩代码  
  3.   ss = s.replace(/\/\*(.|\n)*?\*\//g, ""); //删除注释  
  4.   ss = s.replace(/\s*([\{\}\:\;\,])\s*/g, "$1");  
  5.   ss = s.replace(/\,[\s\.\#\d]*\{/g, "{"); //容错处理  
  6.   ss = s.replace(/;\s*;/g, ";"); //清除连续分号  
  7.   ss = s.match(/^\s*(\S+(\s+\S+)*)\s*$/); //去掉首尾空白  
  8.   return s == null ? "" : s[1];  

获取当前路径 

  1. var currentPageUrl = "" 
  2. if (typeof this.href === "undefined") {  
  3.   currentPageUrl = document.location.toString().toLowerCase();  
  4. } else {  
  5.   currentPageUrl = this.href.toString().toLowerCase();  

字符串长度截取 

  1. function cutstr(str, len) {  
  2.     var temp,  
  3.         icount = 0 
  4.         patrn = /[^\x00-\xff]/,  
  5.         strre = "" 
  6.     for (var i = 0; i < str.length; i++) {  
  7.         if (icount < len - 1) {  
  8.             temp = str.substr(i, 1);  
  9.                 if (patrn.exec(temp) == null) {  
  10.                    icounticount = icount + 1  
  11.             } else {  
  12.                 icounticount = icount + 2  
  13.             }  
  14.             strre += temp  
  15.             } else {  
  16.             break;  
  17.         }  
  18.     }  
  19.     return strre + "..."  

时间日期格式转换 

  1. Date.prototype.format = function(formatStr) {  
  2.   var str = formatStr 
  3.   var Week = ["日", "一", "二", "三", "四", "五", "六"];  
  4.   strstr = str.replace(/yyyy|YYYY/, this.getFullYear());  
  5.   strstr = str.replace(  
  6.     /yy|YY/,  
  7.     this.getYear() % 100 > 9  
  8.       ? (this.getYear() % 100).toString()  
  9.       : "0" + (this.getYear() % 100)  
  10.   );  
  11.   strstr = str.replace(  
  12.     /MM/,  
  13.     this.getMonth() + 1 > 9  
  14.       ? (this.getMonth() + 1).toString()  
  15.       : "0" + (this.getMonth() + 1)  
  16.   );  
  17.   strstr = str.replace(/M/g, this.getMonth() + 1);  
  18.   strstr = str.replace(/w|W/g, Week[this.getDay()]);  
  19.   strstr = str.replace(  
  20.     /dd|DD/,  
  21.     this.getDate() > 9 ? this.getDate().toString() : "0" + this.getDate()  
  22.   );  
  23.   strstr = str.replace(/d|D/g, this.getDate());  
  24.   strstr = str.replace(  
  25.     /hh|HH/,  
  26.     this.getHours() > 9 ? this.getHours().toString() : "0" + this.getHours()  
  27.   );  
  28.   strstr = str.replace(/h|H/g, this.getHours());  
  29.   strstr = str.replace(  
  30.     /mm/,  
  31.     this.getMinutes() > 9  
  32.       ? this.getMinutes().toString()  
  33.       : "0" + this.getMinutes()  
  34.   );  
  35.   strstr = str.replace(/m/g, this.getMinutes());  
  36.   strstr = str.replace(  
  37.     /ss|SS/,  
  38.     this.getSeconds() > 9  
  39.       ? this.getSeconds().toString()  
  40.       : "0" + this.getSeconds()  
  41.   );  
  42.   strstr = str.replace(/s|S/g, this.getSeconds());  
  43.   return str;  
  44. };  
  45. // 或  
  46. Date.prototype.format = function(format) {  
  47.   var o = {  
  48.     "M+": this.getMonth() + 1, //month  
  49.     "d+": this.getDate(), //day  
  50.     "h+": this.getHours(), //hour  
  51.     "m+": this.getMinutes(), //minute  
  52.     "s+": this.getSeconds(), //second  
  53.     "q+": Math.floor((this.getMonth() + 3) / 3), //quarter  
  54.     S: this.getMilliseconds() //millisecond  
  55.   };  
  56.   if (/(y+)/.test(format))  
  57.     formatformat = format.replace(  
  58.       RegExp.$1,  
  59.       (this.getFullYear() + "").substr(4 - RegExp.$1.length)  
  60.     );  
  61.   for (var k in o) {  
  62.     if (new RegExp("(" + k + ")").test(format))  
  63.       formatformat = format.replace(  
  64.         RegExp.$1,  
  65.         RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)  
  66.       );  
  67.   }  
  68.   return format;  
  69. }; 
  70.  alert(new Date().format("yyyy-MM-dd hh:mm:ss")); 

跨浏览器删除事件 

  1. function delEvt(obj, evt, fn) {  
  2.   if (!obj) {  
  3.     return;  
  4.   }  
  5.   if (obj.addEventListener) {  
  6.     obj.addEventListener(evt, fn, false);  
  7.   } else if (oTarget.attachEvent) {  
  8.     obj.attachEvent("on" + evt, fn);  
  9.   } else {  
  10.     obj["on" + evt] = fn;  
  11.   }  

判断是否以某个字符串结束 

  1. String.prototype.endWith = function(s) {  
  2.   var d = this.length - s.length;  
  3.   return d >= 0 && this.lastIndexOf(s) == d;  
  4. }; 

返回脚本内容 

  1. function evalscript(s) {  
  2.   if (s.indexOf("<script") == -1) return s;  
  3.   var p = /<script[^\>]*?>([^\x00]*?)<\/script>/gi;  
  4.   var arr = []; 
  5.    while ((arr = p.exec(s))) {  
  6.     var p1 = /<script[^\>]*?src=\"([^\>]*?)\"[^\>]*?(reload=\"1\")?(?:charset=\"([\w\-]+?)\")?><\/script>/i;  
  7.     var arr1 = [];  
  8.     arr1 = p1.exec(arr[0]);  
  9.     if (arr1) {  
  10.       appendscript(arr1[1], "", arr1[2], arr1[3]);  
  11.     } else {  
  12.       p1 = /<script(.*?)>([^\x00]+?)<\/script>/i;  
  13.       arr1 = p1.exec(arr[0]);  
  14.       appendscript("", arr1[2], arr1[1].indexOf("reload=") != -1);  
  15.     }  
  16.   }  
  17.   return s;  

格式化CSS样式代码 

  1. function formatCss(s) {  
  2.   //格式化代码  
  3.   ss = s.replace(/\s*([\{\}\:\;\,])\s*/g, "$1");  
  4.   ss = s.replace(/;\s*;/g, ";"); //清除连续分号  
  5.   ss = s.replace(/\,[\s\.\#\d]*{/g, "{");  
  6.   ss = s.replace(/([^\s])\{([^\s])/g, "$1 {\n\t$2");  
  7.   ss = s.replace(/([^\s])\}([^\n]*)/g, "$1\n}\n$2");  
  8.   ss = s.replace(/([^\s]);([^\s\}])/g, "$1;\n\t$2");  
  9.   return s;  

获取cookie值 

  1. function getCookie(name) {  
  2.   var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));  
  3.   if (arr != null) return unescape(arr[2]);  
  4.   return null;  

获得URL中GET参数值 

  1. // 用法:如果地址是 test.htm?t1=1&t2=2&t3=3, 那么能取得:GET["t1"], GET["t2"], GET["t3"]  
  2. function getGet() {  
  3.   querystr = window.location.href.split("?");  
  4.   if (querystr[1]) {  
  5.     GETs = querystr[1].split("&");  
  6.     GET = [];  
  7.     for (i = 0; i < GETs.length; i++) {  
  8.       tmp_arr = GETs.split("=");  
  9.       key = tmp_arr[0];  
  10.       GET[key] = tmp_arr[1];  
  11.     }  
  12.   }  
  13.   return querystr[1];  

获取移动设备初始化大小 

  1. function getInitZoom() {  
  2.   if (!this._initZoom) {  
  3.     var screenWidth = Math.min(screen.height, screen.width);  
  4.     if (this.isAndroidMobileDevice() && !this.isNewChromeOnAndroid()) {  
  5.       screenWidthscreenWidth = screenWidth / window.devicePixelRatio;  
  6.     }  
  7.     this._initZoom = screenWidth / document.body.offsetWidth;  
  8.   }  
  9.   return this._initZoom;  

获取页面高度 

  1. function getPageHeight() {  
  2.   var g = document 
  3.     a = g.body,  
  4.     f = g.documentElement,  
  5.     d = g.compatMode == "BackCompat" ? a : g.documentElement;  
  6.   return Math.max(f.scrollHeight, a.scrollHeight, d.clientHeight);  

获取页面scrollLeft 

  1. function getPageScrollLeft() {  
  2.   var a = document 
  3.   return a.documentElement.scrollLeft || a.body.scrollLeft;  

获取页面scrollTop 

  1. function getPageScrollTop() {  
  2.   var a = document 
  3.   return a.documentElement.scrollTop || a.body.scrollTop;  

获取页面可视高度 

  1. function getPageViewHeight() {  
  2.   var d = document 
  3.     a = d.compatMode == "BackCompat" ? d.body : d.documentElement;  
  4.   return a.clientHeight;  

获取页面可视宽度 

  1. function getPageViewWidth() {  
  2.   var d = document 
  3.     a = d.compatMode == "BackCompat" ? d.body : d.documentElement;  
  4.   return a.clientWidth;  

获取页面宽度 

  1. function getPageWidth() {  
  2.   var g = document 
  3.     a = g.body,  
  4.     f = g.documentElement,  
  5.     d = g.compatMode == "BackCompat" ? a : g.documentElement;  
  6.   return Math.max(f.scrollWidth, a.scrollWidth, d.clientWidth);  

获取移动设备屏幕宽度 

  1. function getScreenWidth() {  
  2.   var smallerSide = Math.min(screen.width, screen.height);  
  3.   var fixViewPortsExperiment =  
  4.     rendererModel.runningExperiments.FixViewport ||  
  5.     rendererModel.runningExperiments.fixviewport; 
  6.    var fixViewPortsExperimentfixViewPortsExperimentRunning =  
  7.     fixViewPortsExperiment && fixViewPortsExperiment.toLowerCase() === "new";  
  8.   if (fixViewPortsExperiment) {  
  9.     if (this.isAndroidMobileDevice() && !this.isNewChromeOnAndroid()) {  
  10.       smallerSidesmallerSide = smallerSide / window.devicePixelRatio;  
  11.     }  
  12.   }  
  13.   return smallerSide;  

获取网页被卷去的位置 

  1. function getScrollXY() {  
  2.   return document.body.scrollTop  
  3.     ? {  
  4.         x: document.body.scrollLeft,  
  5.         y: document.body.scrollTop  
  6.       }  
  7.     : {  
  8.         x: document.documentElement.scrollLeft,  
  9.         y: document.documentElement.scrollTop  
  10.       };  

获取URL上的参数 

  1. // 获取URL中的某参数值,不区分大小写  
  2. // 获取URL中的某参数值,不区分大小写,  
  3. // 默认是取'hash'里的参数,  
  4. // 如果传其他参数支持取‘search’中的参数  
  5. // @param {String} name 参数名称  
  6. export function getUrlParam(name, type = "hash") {  
  7.   let newName = name 
  8.     reg = new RegExp("(^|&)" + newName + "=([^&]*)(&|$)", "i"),  
  9.     paramHash = window.location.hash.split("?")[1] || "",  
  10.     paramSearch = window.location.search.split("?")[1] || "",  
  11.     param;  
  12.   type === "hash" ? (param = paramHash) : (param = paramSearch);  
  13.   let result = param.match(reg);  
  14.   if (result != null) {  
  15.     return result[2].split("/")[0];  
  16.   }  
  17.   return null;  

检验URL链接是否有效 

  1. function getUrlState(URL) {  
  2.   var xmlhttp = new ActiveXObject("microsoft.xmlhttp");  
  3.   xmlhttp.Open("GET", URL, false);  
  4.   try {  
  5.     xmlhttp.Send();  
  6.   } catch (e) {  
  7.   } finally {  
  8.     var result = xmlhttp.responseText;  
  9.     if (result) {  
  10.       if (xmlhttp.Status == 200) {  
  11.         return true;  
  12.       } else {  
  13.         return false;  
  14.       }  
  15.     } else {  
  16.       return false;  
  17.     }  
  18.   }  

获取窗体可见范围的宽与高 

  1. function getViewSize() {  
  2.   var de = document.documentElement;  
  3.   var db = document.body;  
  4.   var viewW = de.clientWidth == 0 ? db.clientWidth : de.clientWidth;  
  5.   var viewH = de.clientHeight == 0 ? db.clientHeight : de.clientHeight;  
  6.   return Array(viewW, viewH);  

获取移动设备最大化大小 

  1. function getZoom() {  
  2.   var screenWidth =  
  3.     Math.abs(window.orientation) === 90  
  4.       ? Math.max(screen.height, screen.width)  
  5.       : Math.min(screen.height, screen.width);  
  6.   if (this.isAndroidMobileDevice() && !this.isNewChromeOnAndroid()) {  
  7.     screenWidthscreenWidth = screenWidth / window.devicePixelRatio;  
  8.   }  
  9.   var FixViewPortsExperiment =  
  10.     rendererModel.runningExperiments.FixViewport ||  
  11.     rendererModel.runningExperiments.fixviewport;  
  12.   var FixViewPortsExperimentFixViewPortsExperimentRunning =  
  13.     FixViewPortsExperiment &&  
  14.     (FixViewPortsExperiment === "New" || FixViewPortsExperiment === "new");  
  15.   if (FixViewPortsExperimentRunning) {  
  16.     return screenWidth / window.innerWidth;  
  17.   } else {  
  18.     return screenWidth / document.body.offsetWidth;  
  19.   }  

判断是否安卓移动设备访问 

  1. function isAndroidMobileDevice() {  
  2.   return /android/i.test(navigator.userAgent.toLowerCase());  

判断是否苹果移动设备访问 

  1. function isAppleMobileDevice() {  
  2.   return /iphone|ipod|ipad|Macintosh/i.test(navigator.userAgent.toLowerCase());  

判断是否为数字类型 

  1. function isDigit(value) {  
  2.   var patrn = /^[0-9]*$/; 
  3.    if (patrn.exec(value) == null || value == "") {  
  4.     return false;  
  5.   } else {  
  6.     return true;  
  7.   }  

是否是某类手机型号 

  1. // 用devicePixelRatio和分辨率判断  
  2. const isIphonex = () => {  
  3.   // X XS, XS Max, XR  
  4.   const xSeriesConfig = [  
  5.     {  
  6.       devicePixelRatio: 3,  
  7.       width: 375,  
  8.       height: 812  
  9.     },  
  10.     {  
  11.       devicePixelRatio: 3,  
  12.       width: 414,  
  13.       height: 896  
  14.     },  
  15.     {  
  16.       devicePixelRatio: 2,  
  17.       width: 414,  
  18.       height: 896  
  19.     }  
  20.   ];  
  21.   // h5  
  22.   if (typeof window !== "undefined" && window) {  
  23.     const isIOS = /iphone/gi.test(window.navigator.userAgent);  
  24.     if (!isIOS) return false;  
  25.     const { devicePixelRatio, screen } = window;  
  26.     const { width, height } = screen;  
  27.     return xSeriesConfig.some(  
  28.       item =>  
  29.         item.devicePixelRatio === devicePixelRatio &&  
  30.         item.width === width &&  
  31.         item.height === height  
  32.     );  
  33.   }  
  34.   return false;  
  35. }; 

判断是否移动设备 

  1. function isMobile() {  
  2.   if (typeof this._isMobile === "boolean") {  
  3.     return this._isMobile;  
  4.   }  
  5.   var screenWidth = this.getScreenWidth();  
  6.   var fixViewPortsExperiment =  
  7.     rendererModel.runningExperiments.FixViewport ||  
  8.     rendererModel.runningExperiments.fixviewport;  
  9.   var fixViewPortsExperimentfixViewPortsExperimentRunning =  
  10.     fixViewPortsExperiment && fixViewPortsExperiment.toLowerCase() === "new";  
  11.   if (!fixViewPortsExperiment) {  
  12.     if (!this.isAppleMobileDevice()) {  
  13.       screenWidthscreenWidth = screenWidth / window.devicePixelRatio;  
  14.     }  
  15.   }  
  16.   var isMobileScreenSize = screenWidth < 600 
  17.   var isMobileUserAgent = false 
  18.   this._isMobile = isMobileScreenSize && this.isTouchScreen();  
  19.   return this._isMobile;  

判断吗是否手机号码 

  1. function isMobileNumber(e) {  
  2.   var i =  
  3.       "134,135,136,137,138,139,150,151,152,157,158,159,187,188,147,182,183,184,178" 
  4.     n = "130,131,132,155,156,185,186,145,176" 
  5.     a = "133,153,180,181,189,177,173,170" 
  6.     o = e || "",  
  7.     r = o.substring(0, 3),  
  8.     d = o.substring(0, 4),  
  9.     s =  
  10.       !!/^1\d{10}$/.test(o) &&  
  11.       (n.indexOf(r) >= 0  
  12.         ? "联通"  
  13.         : a.indexOf(r) >= 0  
  14.         ? "电信"  
  15.         : "1349" == d  
  16.         ? "电信"  
  17.         : i.indexOf(r) >= 0  
  18.         ? "移动"  
  19.         : "未知");  
  20.   return s;  

判断是否是移动设备访问 

  1. function isMobileUserAgent() {  
  2.   return /iphone|ipod|android.*mobile|windows.*phone|blackberry.*mobile/i.test(  
  3.     window.navigator.userAgent.toLowerCase()  
  4.   );  

判断鼠标是否移出事件 

  1. function isMouseOut(e, handler) {  
  2.   if (e.type !== "mouseout") {  
  3.     return false;  
  4.   }  
  5.   var reltg = e.relatedTarget  
  6.     ? e.relatedTarget  
  7.     : e.type === "mouseout"  
  8.     ? e.toElement  
  9.     : e.fromElement;  
  10.   while (reltg && reltg !== handler) {  
  11.     reltgreltg = reltg.parentNode;  
  12.   }  
  13.   return reltg !== handler;  

判断是否Touch屏幕 

  1. function isTouchScreen() {  
  2.   return (  
  3.     "ontouchstart" in window ||  
  4.     (window.DocumentTouch && document instanceof DocumentTouch)  
  5.   );  

判断是否为网址 

  1. function isURL(strUrl) {  
  2.   var regular = /^\b(((https?|ftp):\/\/)?[-a-z0-9]+(\.[-a-z0-9]+)*\.(?:com|edu|gov|int|mil|net|org|biz|info|name|museum|asia|coop|aero|[a-z][a-z]|((25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]\d)|\d))\b(\/[-a-z0-9_:\@&?=+,.!\/~%\$]*)?)$/i; 
  3.    if (regular.test(strUrl)) {  
  4.     return true;  
  5.   } else {  
  6.     return false;  
  7.   }  

判断是否打开视窗 

  1. function isViewportOpen() {  
  2.   return !!document.getElementById("wixMobileViewport");  

加载样式文件 

  1. function loadStyle(url) {  
  2.   try {  
  3.     document.createStyleSheet(url);  
  4.   } catch (e) {  
  5.     var cssLink = document.createElement("link");  
  6.     cssLink.rel = "stylesheet" 
  7.     cssLink.type = "text/css" 
  8.     cssLink.href = url 
  9.     var head = document.getElementsByTagName("head")[0];  
  10.     head.appendChild(cssLink);  
  11.   }  

替换地址栏 

  1. function locationReplace(url) {  
  2.   if (history.replaceState) {  
  3.     history.replaceState(null, document.title, url);  
  4.     history.go(0);  
  5.   } else {  
  6.     location.replace(url);  
  7.   }  

解决offsetX兼容性问题 

  1. // 针对火狐不支持offsetX/Y  
  2. function getOffset(e) {  
  3.   var target = e.target, // 当前触发的目标对象  
  4.     eventCoord,  
  5.     pageCoord,  
  6.     offsetCoord;  
  7.   // 计算当前触发元素到文档的距离  
  8.   pageCoord = getPageCoord(target);  
  9.   // 计算光标到文档的距离  
  10.   eventCoord = {  
  11.     X: window.pageXOffset + e.clientX,  
  12.     Y: window.pageYOffset + e.clientY  
  13.   };  
  14.   // 相减获取光标到第一个定位的父元素的坐标  
  15.   offsetCoord = {  
  16.     X: eventCoord.X - pageCoord.X,  
  17.     Y: eventCoord.Y - pageCoord.Y  
  18.   };  
  19.   return offsetCoord;  
  20.  
  21. function getPageCoord(element) {  
  22.   var coord = { X: 0, Y: 0 };  
  23.   // 计算从当前触发元素到根节点为止,  
  24.   // 各级 offsetParent 元素的 offsetLeft 或 offsetTop 值之和  
  25.   while (element) {  
  26.     coord.X += element.offsetLeft;  
  27.     coord.Y += element.offsetTop;  
  28.     elementelement = element.offsetParent;  
  29.   }  
  30.   return coord;  

打开一个窗体通用方法 

  1. function openWindow(url, windowName, width, height) {  
  2.   var x = parseInt(screen.width / 2.0) - width / 2.0;  
  3.   var y = parseInt(screen.height / 2.0) - height / 2.0;  
  4.   var isMSIE = navigator.appName == "Microsoft Internet Explorer";  
  5.   if (isMSIE) {  
  6.     var p = "resizable=1,location=no,scrollbars=no,width=" 
  7.     pp = p + width;  
  8.     pp = p + ",height=";  
  9.     pp = p + height;  
  10.     pp = p + ",left=";  
  11.     pp = p + x;  
  12.     pp = p + ",top=";  
  13.     pp = p + y;  
  14.     retval = window.open(url, windowName, p);  
  15.   } else {  
  16.     var win = window.open(  
  17.       url,  
  18.       "ZyiisPopup",  
  19.       "top=" +  
  20.         y +  
  21.         ",left=" +  
  22.         x +  
  23.         ",scrollbars=" + 
  24.         scrollbars +  
  25.         ",dialog=yes,modal=yes,width=" +  
  26.         width +  
  27.         ",height=" +  
  28.         height +  
  29.         ",resizable=no 
  30.     );  
  31.     eval("try { win.resizeTo(width, height); } catch(e) { }");  
  32.     win.focus();  
  33.   }  

将键值对拼接成URL带参数 

  1. export default const fnParams2Url = obj=> {  
  2.       let aUrl = []  
  3.       let fnAdd = function(key, value) {  
  4.         return key + '=' + value  
  5.       }  
  6.       for (var k in obj) {  
  7.         aUrl.push(fnAdd(k, obj[k]))  
  8.       }  
  9.       return encodeURIComponent(aUrl.join('&'))  
  10.  } 

去掉url前缀 

  1. function removeUrlPrefix(a) {  
  2.   aa = a  
  3.     .replace(/:/g, ":")  
  4.     .replace(/./g, ".")  
  5.     .replace(///g, "/");  
  6.   while (  
  7.     trim(a)  
  8.       .toLowerCase()  
  9.       .indexOf("http://") == 0  
  10.   ) {  
  11.     a = trim(a.replace(/http:\/\//i, ""));  
  12.   }  
  13.   return a;  

替换全部 

  1. String.prototype.replaceAll = function(s1, s2) {  
  2.   return this.replace(new RegExp(s1, "gm"), s2);  
  3. }; 

resize的操作 

  1. (function() {  
  2.   var fn = function() {  
  3.     var w = document.documentElement  
  4.         ? document.documentElement.clientWidth  
  5.         : document.body.clientWidth,  
  6.       r = 1255 
  7.       b = Element.extend(document.body),  
  8.       classname = b.className;  
  9.     if (w < r) {  
  10.       //当窗体的宽度小于1255的时候执行相应的操作  
  11.     } else {  
  12.       //当窗体的宽度大于1255的时候执行相应的操作  
  13.     }  
  14.   };  
  15.   if (window.addEventListener) {  
  16.     window.addEventListener("resize", function() {  
  17.       fn();  
  18.     });  
  19.   } else if (window.attachEvent) {  
  20.     window.attachEvent("onresize", function() {  
  21.       fn();  
  22.     });  
  23.   }  
  24.   fn();  
  25. })(); 

滚动到顶部 

  1. // 使用document.documentElement.scrollTop 或 document.body.scrollTop 获取到顶部的距离,从顶部  
  2. // 滚动一小部分距离。使用window.requestAnimationFrame()来滚动。  
  3. // @example  
  4. // scrollToTop();  
  5. function scrollToTop() {  
  6.   var c = document.documentElement.scrollTop || document.body.scrollTop;  
  7.   if (c > 0) {  
  8.     window.requestAnimationFrame(scrollToTop);  
  9.     window.scrollTo(0, c - c / 8);  
  10.   }  

设置cookie值 

  1. function setCookie(name, value, Hours) {  
  2.   var d = new Date();  
  3.   var offset = 8
  4.    var utc = d.getTime() + d.getTimezoneOffset() * 60000;  
  5.   var nd = utc + 3600000 * offset;  
  6.   var exp = new Date(nd);  
  7.   exp.setTime(exp.getTime() + Hours * 60 * 60 * 1000);  
  8.   document.cookie =  
  9.     name +  
  10.     "=" +  
  11.     escape(value) +  
  12.     ";path=/;expires=" +  
  13.     exp.toGMTString() +  
  14.     ";domain=360doc.com;";  

设为首页 

  1. function setHomepage() {  
  2.   if (document.all) {  
  3.     document.body.style.behavior = "url(#default#homepage)" 
  4.     document.body.setHomePage("http://w3cboy.com");  
  5.   } else if (window.sidebar) {  
  6.     if (window.netscape) {  
  7.       try {  
  8.         netscape.security.PrivilegeManager.enablePrivilege(  
  9.           "UniversalXPConnect"  
  10.         );  
  11.       } catch (e) {  
  12.         alert(  
  13.           "该操作被浏览器拒绝,如果想启用该功能,请在地址栏内输入 about:config,然后将项 signed.applets.codebase_principal_support 值该为true"  
  14.         );  
  15.       }  
  16.     }  
  17.     var prefs = Components.classes[  
  18.       "@mozilla.org/preferences-service;1"  
  19.     ].getService(Components.interfaces.nsIPrefBranch);  
  20.     prefs.setCharPref("browser.startup.homepage", "http://w3cboy.com");  
  21.   } 
  22.  

按字母排序,对每行进行数组排序 

  1. function setSort() {  
  2.   var text = K1.value  
  3.     .split(/[\r\n]/)  
  4.     .sort()  
  5.     .join("\r\n"); //顺序  
  6.   var test = K1.value  
  7.     .split(/[\r\n]/)  
  8.     .sort()  
  9.     .reverse()  
  10.     .join("\r\n"); //反序  
  11.   K1K1.value = K1.value != text ? text : test;  

延时执行 

  1. // 比如 sleep(1000) 意味着等待1000毫秒,还可从 Promise、Generator、Async/Await 等角度实现。  
  2. // Promise  
  3. const sleep = time => {  
  4.   return new Promise(resolve => setTimeout(resolve, time));  
  5. };  
  6. sleep(1000).then(() => {  
  7.   console.log(1);  
  8. });  
  9. // Generator  
  10. function* sleepGenerator(time) {  
  11.   yield new Promise(function(resolve, reject) {  
  12.     setTimeout(resolve, time);  
  13.   });  
  14.  
  15. sleepGenerator(1000)  
  16.   .next()  
  17.   .value.then(() => {  
  18.     console.log(1);  
  19.   });  
  20. //async  
  21. function sleep(time) {  
  22.   return new Promise(resolve => setTimeout(resolve, time));  
  23.  
  24. async function output() {  
  25.   let out = await sleep(1000);  
  26.   console.log(1);  
  27.   return out;  
  28.  
  29. output();  
  30. function sleep(callback, time) {  
  31.   if (typeof callback === "function") {  
  32.     setTimeout(callback, time);  
  33.   }  
  34.  
  35. function output() {  
  36.   console.log(1);  
  37.  
  38. sleep(output, 1000); 

判断是否以某个字符串开头 

  1. String.prototype.startWith = function(s) {  
  2.   return this.indexOf(s) == 0;  
  3. }; 

清除脚本内容 

  1. function stripscript(s) {  
  2.   return s.replace(/<script.*?>.*?<\/script>/gi, "");  

时间个性化输出功能 

  1. /*  
  2. 1、< 60s, 显示为“刚刚” 
  3. 2、>= 1min && < 60 min, 显示与当前时间差“XX分钟前”  
  4. 3、>= 60min && < 1day, 显示与当前时间差“今天 XX:XX”  
  5. 4、>= 1day && < 1year, 显示日期“XX月XX日 XX:XX”  
  6. 5、>= 1year, 显示具体日期“XXXX年XX月XX日 XX:XX”  
  7. */  
  8. function timeFormat(time) {  
  9.   var date = new Date(time),  
  10.     curDate = new Date(),  
  11.     year = date.getFullYear(),  
  12.     month = date.getMonth() + 10,  
  13.     day = date.getDate(),  
  14.     hour = date.getHours(),  
  15.     minute = date.getMinutes(),  
  16.     curYear = curDate.getFullYear(), 
  17.     curHour = curDate.getHours(),  
  18.     timeStr;  
  19.   if (year < curYear) {  
  20.     timeStr = year + "年" + month + "月" + day + "日 " + hour + ":" + minute;  
  21.   } else {  
  22.     var pastTime = curDate - date,  
  23.       pastH = pastTime / 3600000;  
  24.     if (pastH > curHour) {  
  25.       timeStr = month + "月" + day + "日 " + hour + ":" + minute;  
  26.     } else if (pastH >= 1) {  
  27.       timeStr = "今天 " + hour + ":" + minute + "分";  
  28.     } else {  
  29.       var pastM = curDate.getMinutes() - minute;  
  30.       if (pastM > 1) {  
  31.         timeStr = pastM + "分钟前";  
  32.       } else {  
  33.         timeStr = "刚刚" 
  34.       }  
  35.     }  
  36.   }  
  37.   return timeStr;  

全角转换为半角函数 

  1. function toCDB(str) {  
  2.   var result = "" 
  3.   for (var i = 0; i < str.length; i++) {  
  4.     code = str.charCodeAt(i);  
  5.     if (code >= 65281 && code <= 65374) {  
  6.       result += String.fromCharCode(str.charCodeAt(i) - 65248);  
  7.     } else if (code == 12288) {  
  8.       result += String.fromCharCode(str.charCodeAt(i) - 12288 + 32);  
  9.     } else {  
  10.       result += str.charAt(i);  
  11.     }  
  12.   }  
  13.   return result;  

半角转换为全角函数 

  1. function toDBC(str) {  
  2.   var result = "" 
  3.   for (var i = 0; i < str.length; i++) {  
  4.     code = str.charCodeAt(i);  
  5.     if (code >= 33 && code <= 126) {  
  6.       result += String.fromCharCode(str.charCodeAt(i) + 65248);  
  7.     } else if (code == 32) {  
  8.       result += String.fromCharCode(str.charCodeAt(i) + 12288 - 32);  
  9.     } else {  
  10.       result += str.charAt(i);  
  11.     }  
  12.   }  
  13.   return result;  

金额大写转换函数 

  1. function transform(tranvalue) {  
  2.   try {  
  3.     var i = 1 
  4.     var dw2 = new Array("", "万", "亿"); //大单位  
  5.     var dw1 = new Array("拾", "佰", "仟"); //小单位  
  6.     var dw = new Array(  
  7.       "零",  
  8.       "壹",  
  9.       "贰",  
  10.       "叁",  
  11.       "肆",  
  12.       "伍",  
  13.       "陆",  
  14.       "柒",  
  15.       "捌",  
  16.       "玖"  
  17.     );   
  18.     //整数部分用  
  19.     //以下是小写转换成大写显示在合计大写的文本框中  
  20.     //分离整数与小数  
  21.     var source = splits(tranvalue);  
  22.     var num = source[0];  
  23.     var dig = source[1];  
  24.     //转换整数部分  
  25.     var k1 = 0; //计小单位  
  26.     var k2 = 0; //计大单位  
  27.     var sum = 0 
  28.     var str = "" 
  29.     var len = source[0].length; //整数的长度  
  30.     for (i = 1; i <= len; i++) {  
  31.       var n = source[0].charAt(len - i); //取得某个位数上的数字  
  32.       var bn = 0 
  33.       if (len - i - 1 >= 0) {  
  34.         bn = source[0].charAt(len - i - 1); //取得某个位数前一位上的数字  
  35.       }  
  36.       sumsum = sum + Number(n);  
  37.       if (sum != 0) {  
  38.         str = dw[Number(n)].concat(str); //取得该数字对应的大写数字,并插入到str字符串的前面  
  39.         if (n == "0") sum = 0 
  40.       }  
  41.       if (len - i - 1 >= 0) {  
  42.         //在数字范围内  
  43.         if (k1 != 3) {  
  44.           //加小单位  
  45.           if (bn != 0) {  
  46.             str = dw1[k1].concat(str);  
  47.           }  
  48.           k1++;  
  49.         } else {  
  50.           //不加小单位,加大单位  
  51.           k1 = 0 
  52.           var temp = str.charAt(0);  
  53.           if (temp == "万" || temp == "亿")  
  54.             //若大单位前没有数字则舍去大单位  
  55.             strstr = str.substr(1, str.length - 1);  
  56.           str = dw2[k2].concat(str);  
  57.           sum = 0 
  58.         }  
  59.       }  
  60.       if (k1 == 3) {  
  61.         //小单位到千则大单位进一  
  62.         k2++;  
  63.       }  
  64.     }  
  65.     //转换小数部分  
  66.     var strdig = "" 
  67.     if (dig != "") {  
  68.       var n = dig.charAt(0);  
  69.       if (n != 0) {  
  70.         strdig += dw[Number(n)] + "角"; //加数字  
  71.       }  
  72.       var n = dig.charAt(1);  
  73.       if (n != 0) {  
  74.         strdig += dw[Number(n)] + "分"; //加数字  
  75.       }  
  76.     }  
  77.     str += "元" + strdig;  
  78.   } catch (e) {  
  79.     return "0元";  
  80.   }  
  81.   return str;  
  82.  
  83. //拆分整数与小数  
  84. function splits(tranvalue) {  
  85.   var value = new Array("", "");  
  86.   temp = tranvalue.split(".");  
  87.   for (var i = 0; i < temp.length; i++) {  
  88.     value = temp 
  89.   }  
  90.   return value;  

清除空格 

  1. String.prototype.trim = function() {  
  2.   var reExtraSpace = /^\s*(.*?)\s+$/;  
  3.   return this.replace(reExtraSpace, "$1");  
  4. };  
  5. // 清除左空格  
  6. function ltrim(s) {  
  7.   return s.replace(/^(\s*| *)/, "");  
  8.  
  9. // 清除右空格  
  10. function rtrim(s) {  
  11.   return s.replace(/(\s*| *)$/, ""); 
  12.  

随机数时间戳 

  1. function uniqueId() {  
  2.   var a = Math.random,  
  3.     b = parseInt 
  4.   return (  
  5.     Number(new Date()).toString() + b(10 * a()) + b(10 * a()) + b(10 * a())  
  6.   );  

实现utf8解码 

  1. function utf8_decode(str_data) {  
  2.   var tmp_arr = [],  
  3.     i = 0 
  4.     ac = 0 
  5.     c1 = 0 
  6.     c2 = 0 
  7.     c3 = 0 
  8.   str_data += "";  
  9.   while (i < str_data.length) {  
  10.     c1 = str_data.charCodeAt(i);  
  11.     if (c1 < 128) {  
  12.       tmp_arr[ac++] = String.fromCharCode(c1);  
  13.       i++;  
  14.     } else if (c1 > 191 && c1 < 224) {  
  15.       c2 = str_data.charCodeAt(i + 1);  
  16.       tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));  
  17.       i += 2;  
  18.     } else {  
  19.       c2 = str_data.charCodeAt(i + 1);  
  20.       c3 = str_data.charCodeAt(i + 2);  
  21.       tmp_arr[ac++] = String.fromCharCode(  
  22.         ((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)  
  23.       );  
  24.       i += 3;  
  25.     }  
  26.   }  
  27.   return tmp_arr.join("");  

以下是Puxiao投稿推荐的几个函数,用作常见的输入值校验和替换操作,主要针对中国大陆地区的校验规则:

校验是否为一个数字,以及该数字小数点位数是否与参数floats一致

校验规则:

  •  若参数floats有值,则校验该数字小数点后的位数。
  •  若参数floats没有值,则仅仅校验是否为数字。 
  1. function isNum(value,floats=null){  
  2.     let regexp = new RegExp(`^[1-9][0-9]*.[0-9]{${floats}}$|^0.[0-9]{${floats}}$`);  
  3.     return typeof value === 'number' && floats?regexp.test(String(value)):true;  
  4.  
  1. function anysicIntLength(minLength,maxLength){  
  2.     let result_str = '' 
  3.     if(minLength){  
  4.         switch(maxLength){  
  5.             case undefined:  
  6.                 result_strresult_str = result_str.concat(`{${minLength-1}}`);  
  7.                 break;  
  8.             case null:  
  9.                 result_strresult_str = result_str.concat(`{${minLength-1},}`);  
  10.                 break;  
  11.             default:  
  12.                 result_strresult_str = result_str.concat(`{${minLength-1},${maxLength-1}}`);  
  13.         }  
  14.     }else{  
  15.         result_strresult_str = result_str.concat('*');  
  16.     }  
  17.     return result_str;  

校验是否为非零的正整数 

  1. function isInt(value,minLength=null,maxLength=undefined){  
  2.     if(!isNum(value)) return false;  
  3.     let regexp = new RegExp(`^-?[1-9][0-9]${anysicIntLength(minLength,maxLength)}$`);  
  4.     return regexp.test(value.toString());  

校验是否为非零的正整数 

  1. function isPInt(value,minLength=null,maxLength=undefined) {  
  2.     if(!isNum(value)) return false;  
  3.     let regexp = new RegExp(`^[1-9][0-9]${anysicIntLength(minLength,maxLength)}$`);  
  4.     return regexp.test(value.toString());  

校验是否为非零的负整数 

  1. function isNInt(value,minLength=null,maxLength=undefined){  
  2.     if(!isNum(value)) return false;  
  3.     let regexp = new RegExp(`^-[1-9][0-9]${anysicIntLength(minLength,maxLength)}$`);  
  4.     return regexp.test(value.toString());  

校验整数是否在取值范围内

校验规则:

  •  minInt为在取值范围中最小的整数
  •  maxInt为在取值范围中最大的整数 
  1. function checkIntRange(value,minInt,maxInt=9007199254740991){  
  2.     return Boolean(isInt(value) && (Boolean(minInt!=undefined && minInt!=null)?value>=minInt:true) && (value<=maxInt));  

校验是否为中国大陆手机号 

  1. function isTel(value) {  
  2.     return /^1[3,4,5,6,7,8,9][0-9]{9}$/.test(value.toString());  

校验是否为中国大陆传真或固定电话号码 

  1. function isFax(str) {  
  2.     return /^([0-9]{3,4})?[0-9]{7,8}$|^([0-9]{3,4}-)?[0-9]{7,8}$/.test(str);  

校验是否为邮箱地址 

  1. function isEmail(str) {  
  2.     return /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(str);  

校验是否为QQ号码

校验规则:

  •  非0开头的5位-13位整数 
  1. function isQQ(value) {  
  2.     return /^[1-9][0-9]{4,12}$/.test(value.toString());  

校验是否为网址

校验规则:

  •  以https://、http://、ftp://、rtsp://、mms://开头、或者没有这些开头
  •  可以没有www开头(或其他二级域名),仅域名
  •  网页地址中允许出现/%*?@&等其他允许的符号 
  1. function isURL(str) { 
  2.      return /^(https:\/\/|http:\/\/|ftp:\/\/|rtsp:\/\/|mms:\/\/)?[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/.test(str);  

校验是否为不含端口号的IP地址

校验规则:

  •  IP格式为xxx.xxx.xxx.xxx,每一项数字取值范围为0-255
  •  除0以外其他数字不能以0开头,比如02 
  1. function isIP(str) {  
  2.     return /^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])$/.test(str);  

校验是否为IPv6地址

校验规则:

  •  支持IPv6正常格式
  •  支持IPv6压缩格式 
  1. function isIPv6(str){  
  2.     return Boolean(str.match(/:/g)?str.match(/:/g).length<=7:false && /::/.test(str)?/^([\da-f]{1,4}(:|::)){1,6}[\da-f]{1,4}$/i.test(str):/^([\da-f]{1,4}:){7}[\da-f]{1,4}$/i.test(str)); 
  3.  

校验是否为中国大陆第二代居民身份证

校验规则:

  •  共18位,最后一位可为X(大小写均可)
  •  不能以0开头
  •  出生年月日会进行校验:年份只能为18/19/2*开头,月份只能为01-12,日只能为01-31 
  1. function isIDCard(str){  
  2.     return /^[1-9][0-9]{5}(18|19|(2[0-9]))[0-9]{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)[0-9]{3}[0-9Xx]$/.test(str);  

校验是否为中国大陆邮政编码

参数value为数字或字符串

校验规则:

  •  共6位,且不能以0开头 
  1. function isPostCode(value){  
  2.     return /^[1-9][0-9]{5}$/.test(value.toString());  

校验两个参数是否完全相同,包括类型

校验规则:

  •  值相同,数据类型也相同 
  1. function same(firstValue,secondValue){  
  2.     return firstValue===secondValue; 
  3.  

校验字符的长度是否在规定的范围内

校验规则:

  •  minInt为在取值范围中最小的长度
  •  maxInt为在取值范围中最大的长度 
  1. function lengthRange(str,minLength,maxLength=9007199254740991) {  
  2.     return Boolean(str.length >= minLength && str.length <= maxLength);  

校验字符是否以字母开头

校验规则:

  •  必须以字母开头
  •  开头的字母不区分大小写 
  1. function letterBegin(str){  
  2.     return /^[A-z]/.test(str);  

校验字符是否为纯数字(整数)

校验规则:

  •  字符全部为正整数(包含0)
  •  可以以0开头 
  1. function pureNum(str) {  
  2.     return /^[0-9]*$/.test(str);  
  3.  
  1. function anysicPunctuation(str){  
  2.     if(!str) return null;  
  3.     let arr = str.split('').map(item => {  
  4.         return item = '\\' + item;  
  5.     });  
  6.     return arr.join('|');  
  7.  
  1. function getPunctuation(str){  
  2.     return anysicPunctuation(str) || '\\~|\\`|\\!|\\@|\\#|\\$|\\%|\\^|\\&|\\*|\\(|\\)|\\-|\\_|\\+|\\=|\\||\\\|\\[|\\]|\\{|\\}|\\;|\\:|\\"|\\\'|\\,|\\<|\\.|\\>|\\/|\\?'; 
  3.   
  1. function getExcludePunctuation(str){  
  2.     let regexp = new RegExp(`[${anysicPunctuation(str)}]`,'g');  
  3.     return getPunctuation(' ~`!@#$%^&*()-_+=\[]{};:"\',<.>/?'.replace(regexp,''));  

返回字符串构成种类(字母,数字,标点符号)的数量

LIP缩写的由来:L(letter 字母) + I(uint 数字) + P(punctuation 标点符号)

参数punctuation的说明:

  •  punctuation指可接受的标点符号集
  •  若需自定义符号集,例如“仅包含中划线和下划线”,将参数设置为"-_"即可
  •  若不传值或默认为null,则内部默认标点符号集为除空格外的其他英文标点符号:~`!@#$%^&*()-_+=[]{};:"',<.>/? 
  1. function getLIPTypes(str,punctuation=null){  
  2.     let p_regexp = new RegExp('['+getPunctuation(punctuation)+']');  
  3.     return /[A-z]/.test(str) + /[0-9]/.test(str) + p_regexp.test(str);  

校验字符串构成的种类数量是否大于或等于参数num的值。 通常用来校验用户设置的密码复杂程度。

校验规则:

  •  参数num为需要构成的种类(字母、数字、标点符号),该值只能是1-3。
  •  默认参数num的值为1,即表示:至少包含字母,数字,标点符号中的1种
  •  若参数num的值为2,即表示:至少包含字母,数字,标点符号中的2种
  •  若参数num的值为3,即表示:必须同时包含字母,数字,标点符号
  •  参数punctuation指可接受的标点符号集,具体设定可参考getLIPTypes()方法中关于标点符号集的解释。 
  1. function pureLIP(str,num=1,punctuation=null){  
  2.     let regexp = new RegExp(`[^A-z0-9|${getPunctuation(punctuation)}]`);  
  3.     return Boolean(!regexp.test(str) && getLIPTypes(str,punctuation)>= num);  

清除所有空格 

  1. function clearSpaces(str){  
  2.     return str.replace(/[ ]/g,'');  

清除所有中文字符(包括中文标点符号) 

  1. function clearCNChars(str){  
  2.     return str.replace(/[\u4e00-\u9fa5]/g,'');  

清除所有中文字符及空格 

  1. function clearCNCharsAndSpaces(str){  
  2.     return str.replace(/[\u4e00-\u9fa5 ]/g,'');  

除保留标点符号集以外,清除其他所有英文的标点符号(含空格)

全部英文标点符号为: ~`!@#$%^&*()-_+=[]{};:"',<.>/?

参数excludePunctuation指需要保留的标点符号集,例如若传递的值为'_',即表示清除_以外的其他所有英文标点符号。 

  1. function clearPunctuation(str,excludePunctuation=null){  
  2.     let regexp = new RegExp(`[${getExcludePunctuation(excludePunctuation)}]`,'g');  
  3.     return str.replace(regexp,'');  

校验是否包含空格 

  1. function haveSpace(str) {  
  2.     return /[ ]/.test(str);  

校验是否包含中文字符(包括中文标点符号) 

  1. function haveCNChars(str){  
  2.     return /[\u4e00-\u9fa5]/.test(str);  
  3.  

 

责任编辑:庞桂玉 来源: segmentfault
相关推荐

2019-07-08 15:10:17

JS工具函数

2011-04-15 13:02:56

Oracle函数

2020-11-04 12:00:05

JavaScript前端代码

2010-07-30 09:56:02

Flex控件

2010-06-17 17:01:26

开源UML工具

2010-07-26 13:45:14

Perl开发工具

2010-07-15 12:56:55

Perl 开发工具

2011-01-11 10:47:36

Linux网络配置

2010-08-03 14:18:02

Flex开发工具

2010-11-12 11:00:11

SQL SERVER内

2010-07-19 15:01:26

Perl数学函数

2019-09-27 16:32:17

虚拟机LinuxDocker

2011-02-28 10:34:45

Android

2010-06-12 13:59:12

2023-04-27 08:15:09

2009-07-31 14:26:38

JavaScript函C#函数

2009-08-06 16:01:09

C#字符串函数大全

2010-07-14 16:35:52

Perl字符串处理函数

2011-09-06 14:10:18

MTK系统时间

2010-09-07 08:27:17

DB2常用函数
点赞
收藏

51CTO技术栈公众号