封装了开发中常用的操作
并添加了一些扩展方法供调用
var util = { //获取Url中的参数(不支持中文) getParams: function() { var url = location.search; //获取url中"?"符后的字串 var params = new Object(); if (url.indexOf("?") != -1) { var str = url.substr(1); strs = str.split("&"); for (var i = 0; i < strs.length; i++) { params[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]); } } return params; }, //获取Url中的参数(支持中文) getUrlVars:function(){ var vars = [], hash; var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); for (var i = 0; i < hashes.length; i++) { hash = hashes[i].split('='); //vars.push(hash[0]); vars[hash[0]] = decodeURI(hash[1]); } return vars; }, //生成guid guid:function(){ function S4() { return (((1+Math.random())*0x10000)|0).toString(16).substring(1); } return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4()); }, security:{ //加密字符串(明文,秘钥) encrypt:function(str,secretKey){ if (secretKey == null || secretKey.length <= 0) { return "Please enter a password with which to encrypt the message."; } var prand = ""; for (var i = 0; i < secretKey.length; i++) { prand += secretKey.charCodeAt(i).toString(); } var sPos = Math.floor(prand.length / 5); var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos * 2) + prand.charAt(sPos * 3) + prand.charAt(sPos * 4) + prand.charAt(sPos * 5)); var incr = Math.ceil(secretKey.length / 2); var modu = Math.pow(2, 31) - 1; if (mult < 2) { return "Algorithm cannot find a suitable hash. Please choose a different password. \nPossible considerations are to choose a more complex or longer password."; return null; } var salt = Math.round(Math.random() * 1000000000) % 100000000; prand += salt; while (prand.length > 10) { prand = (parseInt(prand.substring(0, 10)) + parseInt(prand.substring(10, prand.length))).toString(); } prand = (mult * prand + incr) % modu; var enc_chr = ""; var enc_str = ""; for (var i = 0; i < str.length; i++) { enc_chr = parseInt(str.charCodeAt(i) ^ Math.floor((prand / modu) * 255)); if (enc_chr < 16) { enc_str += "0" + enc_chr.toString(16); } else enc_str += enc_chr.toString(16); prand = (mult * prand + incr) % modu; } salt = salt.toString(16); while (salt.length < 8) salt = "0" + salt; enc_str += salt; return enc_str; }, //解密字符串(密文,秘钥) decrypt:function(str, secretKey){ if (str == null || str.length < 8) { return "A salt value could not be extracted from the encrypted message because it's length is too short. The message cannot be decrypted."; } if (secretKey == null || secretKey.length <= 0) { return "Please enter a password with which to decrypt the message."; } var prand = ""; for (var i = 0; i < secretKey.length; i++) { prand += secretKey.charCodeAt(i).toString(); } var sPos = Math.floor(prand.length / 5); var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos * 2) + prand.charAt(sPos * 3) + prand.charAt(sPos * 4) + prand.charAt(sPos * 5)); var incr = Math.round(secretKey.length / 2); var modu = Math.pow(2, 31) - 1; var salt = parseInt(str.substring(str.length - 8, str.length), 16); str = str.substring(0, str.length - 8); prand += salt; while (prand.length > 10) { prand = (parseInt(prand.substring(0, 10)) + parseInt(prand.substring(10, prand.length))).toString(); } prand = (mult * prand + incr) % modu; var enc_chr = ""; var enc_str = ""; for (var i = 0; i < str.length; i += 2) { enc_chr = parseInt(parseInt(str.substring(i, i + 2), 16) ^ Math.floor((prand / modu) * 255)); enc_str += String.fromCharCode(enc_chr); prand = (mult * prand + incr) % modu; } return enc_str; } }, array:{ uniq:function(arr){ var temp = []; //一个新的临时数组 for (var i = 0; i < arr.length; i++) { if (temp.indexOf(arr[i]) == -1) { temp.push(arr[i]); } } return temp; }, //ES6数组去重(适用于对象数组) uniqES6:function(arr){ return Array.from(new Set(arr)); }, //将数组乱序输出 upset:function (arr){ return arr.sort(function(){ return Math.random() - 0.5}); }, //随机获取数组中的某个元素 getRandomItem :function (arr) { return arr[Math.floor(Math.random() * arr.length)]; }, //返回某个元素在数组中出现的次数 getCount:function (arr, ele) { var num = 0; for (var i = 0, len = arr.length; i < len; i++) { if (ele == arr[i]) { num++; } } return num; }, //简单数组排序,针对数字数组 sort:function(arr,type){ if(type=="desc"){ arr.sort(function(a,b){ return b-a ; }) ; } if(type=="asc"){ arr.sort(function(a,b){ return a-b ; }) ; } return arr ; }, //数字数组 getMaxMin:function(arr){ return {max:Math.max.apply(null,arr),min:Math.min.apply(null,arr)} }, removeItem: function (array, value) { remove(array, value); function remove(arr){ var index = array.indexOf(value); if (index > -1) { array.splice(index, 1); remove(array,value); } } } }, date:{ //格式化日期字符串为指定格式 format:function(str, format){ if (str != null) { var date = new Date(parseInt(str.replace("/Date(", "").replace(")/", ""), 10)); return getDateResult(date,format); } }, getCurrent:function(format){ var date = new Date(); var month = date.getMonth() + 1; var strDate = date.getDate(); if (month >= 1 && month <= 9) { month = "0" + month; } if (strDate >= 0 && strDate <= 9) { strDate = "0" + strDate; } return getDateResult(date,format); }, //获取星期几 getWeek:function(date){ return "星期" + "日一二三四五六".charAt(new Date(date).getDay()); }, //为日期添加指定天数 addDay:function(days,format){ var date=new Date(); date.setMilliseconds(date.getMilliseconds()+(days * 24 * 60 * 60 * 1000)); return getDateResult(date,format); } }, string:{ //字母大小写切换 1:首字母大写 2:首页母小写 3:大小写转换 4:全部大写 5:全部小写 changeCase: function (str,type){ function ToggleCase(str) { var itemText = "" str.split("").forEach(function (item) { if (/^([a-z]+)/.test(item)) { itemText += item.toUpperCase(); }else if (/^([A-Z]+)/.test(item)) { itemText += item.toLowerCase(); }else{ itemText += item; } }); return itemText; } switch (type) { case 1: return str.replace(/^(\w)(\w+)/, function (v, v1, v2) { return v1.toUpperCase() + v2.toLowerCase(); }); case 2: return str.replace(/^(\w)(\w+)/, function (v, v1, v2) { return v1.toLowerCase() + v2.toUpperCase(); }); case 3: return ToggleCase(str); case 4: return str.toUpperCase(); case 5: return str.toLowerCase(); default: return str; } }, //去除字符串最后一位 removeLastChar:function(str){ return str.substring(0, str.length - 1); }, //判断是否中文 isChinese:function(str){ var str = str.replace(/(^\s*)|(\s*$)/g,''); return /^[\u4E00-\uFA29]*$/.test(str) && (!/^[\uE7C7-\uE7F3]*$/.test(str)); }, //判断是否包含中文 isContainsChinese:function(str){ var reg = new RegExp("[\\u4E00-\\u9FFF]+","g"); return reg.test(str); }, //判断是否为邮箱 isEmail:function(str){ return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str); }, //判断是否为IP isIP:function(str){ var reg = /^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$/; return reg.test(str); }, //判断是否为身份证(只考虑数字长度和结尾X) isIDCard:function(str){ var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/; return reg.test(str); }, //判断是否为手机号码 isMobile:function(str){ return /^1[35]\d{9}/.test(str); }, isTel:function(str){ return /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}$/.test(str); }, //判断是否为数字(整数/小数) isNumber:function(str){ return /^(-?\d+)(\.\d+)?$/.test(str); }, //逆序 reverse:function(str){ return str.split("").reverse().join(""); }, //保留数字 getNum:function(str){ return str.replace(/[^d]/g, ""); } }, localStorage:{ get:function(key){ return window.localStorage.getItem(key); }, set:function(key,value){ window.localStorage.setItem(key, value); } }, //用户关闭具体的浏览器标签页,数据也会被删除 sessionStorage:{ get:function(key){ return window.sessionStorage.getItem(key); }, set:function(key,value){ window.sessionStorage.setItem(key, value); } } } function getDateResult(date,format){ var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1; var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate(); var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(); var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(); var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); if (format == 'datetime') return date.getFullYear() + "-" + month + "-" + day + ' ' + hours + ':' + minutes + ':' + seconds; else if (format == 'datetimeshort') return date.getFullYear() + "-" + month + "-" + day + ' ' + hours + ':' + minutes; else if (format == 'date') return date.getFullYear() + "-" + month + "-" + day; else if (format == 'cdate') return date.getFullYear() + "年" + month + "月" + day + '日'; else if(format == 'cdatefull') return date.getFullYear() + "年" + month + "月" + day + '日' + ' ' + hours + '点' + minutes + '分' + seconds + '秒'; } /*================扩展方法===================*/ //判断字符串是否以某字符结尾 String.prototype.endWith = function (str) { var d = this.length - str.length; return (d >= 0 && this.lastIndexOf(str) == d) } //判断字符串是否以某字符开始 String.prototype.startWith = function (str) { var reg = new RegExp("^" + str); return reg.test(this); } //去除前后空格 String.prototype.trim = function () { return this.replace(/(^\s*)|(\s*$)/g, ""); } //去除所有空格 String.prototype.atrim = function () { return this.replace(/\s+/g,''); } String.prototype.ltrim = function(c) { if(c){ if(c.constructor == Number && c > 0){ //参数为整数,删除指定位数的字符 var str = this.substr(0,c); return this.replace(new RegExp("^"+str+"*"), ''); } //删除尾部指定字符串 return this.replace(new RegExp("^"+c+"*"), ''); }else{ //不传参,删除字符串尾部所有空格 return this.replace(/(^\s*)/g, ""); } } String.prototype.rtrim = function (c) { if(c){ if(c.constructor == Number && c > 0){ //参数为整数,删除指定位数的字符 var str = this.substr(this.length-c); return this.replace(new RegExp(""+str+"$"), ''); } //删除尾部指定字符串 return this.replace(new RegExp(""+c+"$"), ''); }else{ //不传参,删除字符串尾部所有空格 return this.replace(/(\s*$)/g, ""); } } //数组添加元素 Array.prototype.add = function(item){ this.push(item); } //数组添加多个元素 Array.prototype.addRange = function(items){ var length = items.length; if(length!=0){ for (var index = 0; index < length; index++) { this.push(items[index]); } } } //清空数组 Array.prototype.clear = function(){ if(this.length>0){ this.splice(0,this.length); } } //数组是否为空 Array.prototype.isEmpty = function(){ if(this.length == 0){ return true; } else{ return false; } } //克隆数组 Array.prototype.clone = function(){ var clonedArray = []; var length = this.length; for (var index = 0; index < length; index++) { clonedArray[index] = this[index]; } return clonedArray; } //数组是否包含元素 Array.prototype.contains = function(item){ var index = this.indexOf(item); return (index>=0); } //把数组的第一个元素从其中删除,并返回第一个元素的值 Array.prototype.dequeue = function(){ return this.shift(); } //返回指定值的下标 Array.prototype.indexOf = function(item){ var length = this.length; if(length!=0){ for (var index = 0; index < length; index++) { if(this[index] == item){ return index; } } } return -1; } //向/从数组中添加/删除项目,然后返回被删除的项目 Array.prototype.insert = function(index,item){ this.splice(index,0,item); } //移除指定元素 Array.prototype.remove = function(item){ var array = this; remove(array,item); function remove(array,item) { var index = array.indexOf(item); if(index >= 0){ array.splice(index,1); remove(array,item); } } } //移除指定下标的元素 Array.prototype.removeAt = function(index){ this.splice(index,1); } //获取字符数组 String.prototype.toCharArray = function(){ return this.split(""); }