封装了开发中常用的操作

并添加了一些扩展方法供调用

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("");
}

JS工具类的更多相关文章

  1. 分享非常好用的前端分页js工具类 灵活 简单易懂

    分享自己封装的前端分页js工具类  下面是默认样式效果截图 可以随意更改js及css 很灵活 /** * pageSize, 每页显示数 * pageIndex, 当前页数 * pageCount 总 ...

  2. JS 工具类

    之前工作用的JavaScript比较多,总结了一下工具类,和大家分享一下,有不足之处还请多多见谅!! 1. 数组工具类(arrayUtils) var arrayUtils = {}; (functi ...

  3. Rhino+envjs-1.2.js 在java运行网站js 工具类

    java爬虫遇到个页面加密的东西,找了些资料学习学习 做了个java运行js的工具类,希望对大家有用,其中用到client(获取js)可以自行换成自己的client.主要是用了 Rhino就是Java ...

  4. js工具类的封装

    common.js原生js实现的大多工具方法都将放在common文件中 布局rem.js,vue开发时,我们只需要将rem.js再main.js中import 引入即可 (function(win, ...

  5. 一些通用的js工具类,添加自定义插件

    common_t.js /** * 通用工具组件 对原有的工具进行封装,自定义某方法统一处理<br> * ^_^ * * Author: em.D * Date: 2016-05-17 * ...

  6. js工具类大全

    /********** 日期处理函数 *********/<script type="text/javascript" src="${springMacroRequ ...

  7. js工具类 ----正则

    function(value){  if(value){   var reg=new RegExp("^[a-zA-Z0-9_-]+$");   return reg.test(v ...

  8. html传参数 js工具类

    var QueryUtils = { GetQueryString: function (name) { var reg = new RegExp("(^|&)" + na ...

  9. js 时间戳转yyyy-MM-dd HH-mm-ss工具类

    转载自:https://blog.csdn.net/shan1774965666/article/details/55049819 在web开发中,我们经常需要用js将时间戳转yyyy-MM-dd H ...

随机推荐

  1. 纵观 jBPM:从 jBPM3 到 jBPM5 以及 Activiti5

    https://www.infoq.cn/article/rh-jbpm5-activiti5# 对jBPM来说,今年最大的事件莫过于 jBPM 的创建者Tom Baeyens离开 JBoss 了.T ...

  2. winform 打印时的默认单位

    通过设置Graphics.PageUnit,是枚举类型GraphicsUnit,默认是display(指定显示设备的度量单位. 通常,视频显示使用的单位是像素:打印机使用的单位是 1/100 英寸.)

  3. 删除DataTable的指定行(Lambda)

    DataTable dtTcu = GetAllTcuInfoBySdId(sdId); DataTable dtToesm = GetAllToesmBySdId(sdId); foreach (D ...

  4. EL表达式取Map,List值的总结

    EL表达式取Map中的值:后台action 中: Map map = new HashMap(); map.put(key1,value1); map.put(key2,value2); map.pu ...

  5. dll导出函数的两种方式的比较

    最初的网页链接已经挂了, 在此贴一个中间的转载链接 https://blog.csdn.net/zhazhiqiang/article/details/51577523 一 概要 vs中导出 dll的 ...

  6. asp代码写的,微信会员报名转发分享带上下级和邀约人关系并且能微信支付asp编号的

    昨天晚上应一个客户要求写了一套代码,实现的功能是: 在微信公众号上注册会员,获取用户的头像和微信名称,进入会员中心报名,报名成功成功后,他如果转发链接给别人,别人打开后则成为他的下级,上面那个算是一个 ...

  7. Docker镜像仓库Harbor搭建及配置

    一.harbor简介 Harbor是一个用于存储和分发Docker镜像的企业级Registry服务器,通过添加一些企业必需的功能特性,例如安全.标识和管理等,扩展了开源Docker Distribut ...

  8. Spring boot 自定义拦截器

    1.新建一个类实现HandlerInterceptor接口,重写接口的方法 package com.zpark.interceptor; import com.zpark.tools.Constant ...

  9. CentOS安装Python模块cx_Oracle

    在线安装 $ wget https://bootstrap.pypa.io/get-pip.py$ python get-pip.py$ pip -V #查看pip版本 或者将网页中的代码复制到get ...

  10. frist Django app — 一、 创建工程

    缘起 既然python都学了,学习python的时候感觉是相见恨晚,一种新的编程语言带给我一种新的思考问题的方式,为了巩固学过的东西并进一步学习python,就想学学Django,看看会不会带给我关于 ...