发布一个JavaScript工具类库jutil

开发 前端
都说好的设计是易于理解的,不用过多介绍,而这也是我现在想达到的目标,因此下面的介绍会比较简单,如果大家哪个地方看不明白或有更好的建议,请提出来,我再优化。

由来

工作中jQuery用的比较多,但jQuery再强大也有些方法是没有的,以前的做法就是东拼西凑,今天终于下定决心把平时用到的一些方法加以整理,这就是jutil的由来。

当前只有17个方法,涉及到的有Array、HTML、Cookie & localStorage、Date、String。这些方法都采用了原生的JS,不依赖于jQuery。

都说好的设计是易于理解的,不用过多介绍,而这也是我现在想达到的目标,因此下面的介绍会比较简单,如果大家哪个地方看不明白或有更好的建议,请提出来,我再优化。

Array相关  

jutil.arrayDistinct(Array)

jutil.arrayIndexOf(Array,Item)

实现代码如下:

  1.  arrayDistinct: function (arr) {  
  2.     var tempArr = {};  
  3.     for (var i = 0; i < arr.length; i++) {  
  4.         if (tempArr[arr[i] + 1]) {  
  5.             arr.splice(i, 1);  
  6.             i--;  
  7.             continue;  
  8.         }  
  9.         tempArr[arr[i] + 1] = true;  
  10.     }  
  11.     tempArr = null;  
  12.     return arr;  
  13. },  
  14. arrayIndexOf: function (arr, obj, iStart) {  
  15.     if (Array.prototype.indexOf) {  
  16.         return arr.indexOf(obj, (iStart || 0));  
  17.     }  
  18.     else {  
  19.         for (var i = (iStart || 0), j = arr.length; i < j; i++) {  
  20.             if (arr[i] === obj) {  
  21.                 return i;  
  22.             }  
  23.         }  
  24.         return -1;  
  25.     }  
  26. }, 

#p#

HTML相关  

jutil.htmlEncode(sHtml)

jutil.htmlDecode(sHtml)

实现代码如下:

  1. htmlEncode: function (sHtml) {  
  2.     var div = this.document.createElement("div"),  
  3.         text = this.document.createTextNode(sHtml);  
  4.     div.appendChild(text);  
  5.     return div.innerHTML;  
  6. },  
  7. htmlDecode: function (sHtml) {  
  8.     var div = this.document.createElement("div");  
  9.     div.innerHTML = sHtml;  
  10.     return div.innerText || div.textContent;  
  11. }, 

如果有用jQuery,上面代码可以进一步简化为:

  1. htmlEncode: function (sHtml) {  
  2.     return $("div").text(sHtml).html();  
  3. },  
  4. htmlDecode: function (sHtml) {  
  5.     return $("div").html(sHtml).text();  
  6. }, 

#p#

Cookie & localStorage相关

jutil.getCookie(sKey)

jutil.setCookie(sKey, sValue, iExpireSeconds)

jutil.deleteCookie(sKey)

jutil.getStorage(sKey)//如果浏览器支持HTML5本地存储(localStorage)优先用本地存储,否则用cookie,下同

jutil.setStorage(sKey, sValue, iExpireSeconds)

jutil.deleteStorage(sKey)

实现代码如下:

  1. getCookie: function (sKey) {  
  2.     if (!sKey)  
  3.         return "";  
  4.     if (document.cookie.length > 0) {  
  5.         var startIndex = document.cookie.indexOf(sKey + "=")  
  6.         if (startIndex != -1) {  
  7.             startIndex = startIndex + sKey.length + 1  
  8.             var endIndex = document.cookie.indexOf(";", startIndex)  
  9.             if (endIndex == -1) {  
  10.                 endIndex = document.cookie.length;  
  11.             }  
  12.             return decodeURIComponent(document.cookie.substring(startIndex, endIndex));  
  13.         }  
  14.     }  
  15.     return "" 
  16. },  
  17. setCookie: function (sKey, sValue, iExpireSeconds) {  
  18.     if (!sKey)  
  19.         return;  
  20.     var expireDate = new Date();  
  21.     expireDate.setTime(expireDate.getTime() + iExpireSeconds * 1000);  
  22.     this.document.cookie = sKey + "=" + encodeURIComponent(sValue) +   
  23.     ";expires=" + expireDate.toGMTString() + ";";  
  24. },  
  25. deleteCookie: function (sKey) {  
  26.     if (!sKey)  
  27.         return;  
  28.     this.document.cookie = sKey + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';  
  29. },  
  30. getStorage: function (sKey) {  
  31.     if (!sKey)  
  32.         return;  
  33.     if (window.localStorage) {  
  34.         return decodeURIComponent(localStorage.getItem(sKey));  
  35.     }  
  36.     else {  
  37.         return this.getCookie(sKey);  
  38.     }  
  39. },  
  40. setStorage: function (sKey, sValue, iExpireSeconds) {  
  41.     if (!sKey)  
  42.         return;  
  43.     if (window.localStorage) {  
  44.         localStorage.setItem(sKey, encodeURIComponent(sValue));  
  45.     }  
  46.     else {  
  47.         this.setCookie(sKey, sValue, iExpireSeconds);  
  48.     }  
  49. },  
  50. deleteStorage: function (sKey) {  
  51.     if (!sKey)  
  52.         return;  
  53.     if (window.localStorage) {  
  54.         localStorage.removeItem(sKey);  
  55.     }  
  56.     else {  
  57.         this.deleteCookie(sKey);  
  58.     }  
  59. }, 

#p#

Date相关  

jutil.daysInFebruary(obj)//obj:数字(如2012)或时间(如new Date())

jutil.daysInYear(obj)//obj:数字(如2012)或时间(如new Date())

jutil.dateFormat(date, sFormat, sLanguage)//sFormat:yyyy为年,MM为月,DD为日,hh为时,mm为分,ss为秒,MMM为月份,EEE为星期。sLanguage:默认为中文,可以设置成英文(en)

jutil.dateDiff(biggerDate, smallerDate)

jutil.dateInterval(biggerDate, smallerDate)

从名子大家可能看不出最后两个方法的区别,这里命名可能是有些问题,大家有没有推荐的?

dateDiff表示两个时间之间相隔多长时间,返回的是"10分钟"、"2天"等字符串,一般用在要显示"XX分钟前"、"XX天前"时。

dateInterval表示两个时间精确差(精确到秒),返回的是"1天:1小时:1分钟:1秒"这样的字符串。

实现代码如下:

  1. daysInFebruary: function (obj) {  
  2.     var year = 0;  
  3.     if (obj instanceof Date) {  
  4.         year = obj.getFullYear();  
  5.     }  
  6.     else if (typeof obj === "number") {  
  7.         year = obj;  
  8.     }  
  9.     else {  
  10.         return 0;  
  11.     }  
  12.     if (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) {  
  13.         return 29;  
  14.     }  
  15.     return 28;  
  16. },  
  17. daysInYear: function (obj) {  
  18.     var year = 0;  
  19.     if (obj instanceof Date) {  
  20.         year = obj.getFullYear();  
  21.     }  
  22.     else if (typeof obj === "number") {  
  23.         year = obj;  
  24.     }  
  25.     else {  
  26.         return 0;  
  27.     }  
  28.     if (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) {  
  29.         return 366;  
  30.     }  
  31.     return 365;  
  32. },  
  33. dateFormat: function (date, sFormat, sLanguage) {  
  34.     var time = {};  
  35.     time.Year = date.getFullYear();  
  36.     time.TYear = ("" + time.Year).substr(2);  
  37.     time.Month = date.getMonth() + 1;  
  38.     time.TMonth = time.Month < 10 ? "0" + time.Month : time.Month;  
  39.     time.Day = date.getDate();  
  40.     time.TDay = time.Day < 10 ? "0" + time.Day : time.Day;  
  41.     time.Hour = date.getHours();  
  42.     time.THour = time.Hour < 10 ? "0" + time.Hour : time.Hour;  
  43.     time.hour = time.Hour < 13 ? time.Hour : time.Hour - 12;  
  44.     time.Thour = time.hour < 10 ? "0" + time.hour : time.hour;  
  45.     time.Minute = date.getMinutes();  
  46.     time.TMinute = time.Minute < 10 ? "0" + time.Minute : time.Minute;  
  47.     time.Second = date.getSeconds();  
  48.     time.TSecond = time.Second < 10 ? "0" + time.Second : time.Second;  
  49.     time.Millisecond = date.getMilliseconds();  
  50.     time.Week = date.getDay();  
  51.  
  52.     var MMMArrEn = ["Jan""Feb""Mar""Apr""May""Jun""Jul""Aug""Sep""Oct""Nov""Dec"],  
  53.         MMMArr = ["一月""二月""三月""四月""五月""六月""七月""八月""九月""十月""十一月""十二月"],  
  54.         WeekArrEn = ["Sun""Mon""Tue""Web""Thu""Fri""Sat"],  
  55.         WeekArr = ["星期日""星期一""星期二""星期三""星期四""星期五""星期六"],  
  56.         oNumber = time.Millisecond / 1000;  
  57.  
  58.     if (sFormat != undefined && sFormat.replace(/\s/g, "").length > 0) {  
  59.         if (sLanguage != undefined && sLanguage === "en") {  
  60.             MMMArr = MMMArrEn.slice(0);  
  61.             WeekArr = WeekArrEn.slice(0);  
  62.         }  
  63.         sFormat = sFormat.replace(/yyyy/ig, time.Year)  
  64.         .replace(/yyy/ig, time.Year)  
  65.         .replace(/yy/ig, time.TYear)  
  66.         .replace(/y/ig, time.TYear)  
  67.         .replace(/MMM/g, MMMArr[time.Month - 1])  
  68.         .replace(/MM/g, time.TMonth)  
  69.         .replace(/M/g, time.Month)  
  70.         .replace(/dd/ig, time.TDay)  
  71.         .replace(/d/ig, time.Day)  
  72.         .replace(/HH/g, time.THour)  
  73.         .replace(/H/g, time.Hour)  
  74.         .replace(/hh/g, time.Thour)  
  75.         .replace(/h/g, time.hour)  
  76.         .replace(/mm/g, time.TMinute)  
  77.         .replace(/m/g, time.Minute)  
  78.         .replace(/ss/ig, time.TSecond)  
  79.         .replace(/s/ig, time.Second)  
  80.         .replace(/fff/ig, time.Millisecond)  
  81.         .replace(/ff/ig, oNumber.toFixed(2) * 100)  
  82.         .replace(/f/ig, oNumber.toFixed(1) * 10)  
  83.         .replace(/EEE/g, WeekArr[time.Week]);  
  84.     }  
  85.     else {  
  86.         sFormat = time.Year + "-" + time.Month + "-" + time.Day + " " + time.Hour + ":" + time.Minute + ":" + time.Second;  
  87.     }  
  88.     return sFormat;  
  89. },  
  90. dateDiff: function (biggerDate, smallerDate) {  
  91.     var intervalSeconds = parseInt((biggerDate - smallerDate) / 1000);  
  92.     if (intervalSeconds < 60) {  
  93.         return intervalSeconds + "秒";  
  94.     }  
  95.     else if (intervalSeconds < 60 * 60) {  
  96.         return Math.floor(intervalSeconds / 60) + "分钟";  
  97.     }  
  98.     else if (intervalSeconds < 60 * 60 * 24) {  
  99.         return Math.floor(intervalSeconds / (60 * 60)) + "小时";  
  100.     }  
  101.     else if (intervalSeconds < 60 * 60 * 24 * 7) {  
  102.         return Math.floor(intervalSeconds / (60 * 60 * 24)) + "天";  
  103.     }  
  104.     else if (intervalSeconds < 60 * 60 * 24 * 31) {  
  105.         return Math.floor(intervalSeconds / (60 * 60 * 24 * 7)) + "周";  
  106.     }  
  107.     else if (intervalSeconds < 60 * 60 * 24 * 365) {  
  108.         return Math.floor(intervalSeconds / (60 * 60 * 24 * 30)) + "月";  
  109.     }  
  110.     else if (intervalSeconds < 60 * 60 * 24 * 365 * 1000) {  
  111.         return Math.floor(intervalSeconds / (60 * 60 * 24 * 365)) + "年";  
  112.     }  
  113.     else {  
  114.         return Math.floor(intervalSeconds / (60 * 60 * 24)) + "天";  
  115.     }  
  116. },  
  117. dateInterval: function (biggerDate, smallerDate) {  
  118.     var intervalSeconds = parseInt((biggerDate - smallerDate) / 1000),  
  119.         day = Math.floor(intervalSeconds / (60 * 60 * 24)),  
  120.         hour = Math.floor((intervalSeconds - day * 24 * 60 * 60) / 3600),  
  121.         minute = Math.floor((intervalSeconds - day * 24 * 60 * 60 - hour * 3600) / 60),  
  122.         second = Math.floor(intervalSeconds - day * 24 * 60 * 60 - hour * 3600 - minute * 60);  
  123.     return day + "天:" + hour + "小时:" + minute + "分钟:" + second + "秒";  
  124. }, 

#p#

String相关

jutil.replaceURLWithHTMLLinks(sText, bBlank)

jutil.getLength(sVal, bChineseDouble)

这个就比较简单了,直接上代码:

  1. replaceURLWithHTMLLinks: function (sText, bBlank) {  
  2.     var pattern = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;  
  3.     if (bBlank) {  
  4.         sText = sText.replace(pattern, "<a target='_blank' href='$1'>$1</a>");  
  5.     }  
  6.     else {  
  7.         sText = sText.replace(pattern, "<a href='$1'>$1</a>");  
  8.     }  
  9.     return sText;  
  10. },  
  11. getLength: function (sVal, bChineseDouble) {  
  12.     var chineseRegex = /[\u4e00-\u9fa5]/g;  
  13.     if (bChineseDouble != undefined && bChineseDouble === false) {  
  14.         return sVal.length;  
  15.     }  
  16.     else {  
  17.         if (chineseRegex.test(sVal)) {  
  18.             return sVal.replace(chineseRegex, "zz").length;  
  19.         }  
  20.         return sVal.length;  
  21.     }  

测试代码

测试效果:

小结

后面会继续添加正则方面的内容,本文也会持续更新。目前JS下载链接:http://files.cnblogs.com/artwl/jutil.js

原文链接:http://www.cnblogs.com/artwl/archive/2012/07/09/2583114.html

责任编辑:张伟 来源: Artwl的博客
相关推荐

2017-07-18 18:06:00

JavaScript框架类库

2013-04-08 10:54:51

Javascript

2022-12-09 15:02:44

2014-02-14 09:37:01

JavascriptDOM

2020-12-08 06:23:05

LockSupport线程工具

2017-12-14 16:55:33

2021-05-19 22:23:56

PythonJavaScript数据

2012-12-12 09:47:56

JavaScript

2022-12-05 14:39:33

Javascript工具

2017-05-02 11:30:44

JavaScript数组惰性求值库

2023-12-07 09:44:29

2012-02-16 10:12:23

JavaScript

2011-03-24 09:34:41

SPRING

2022-05-23 08:05:14

benchstat工具Go

2014-12-17 09:40:22

dockerLinuxPaaS

2011-11-03 09:13:27

JavaScript

2020-09-02 07:22:17

JavaScript插件框架

2012-04-10 13:37:28

JavaScript

2022-03-24 09:13:54

Mybatis加密解密

2023-04-26 01:29:05

OkHttp3工具方式
点赞
收藏

51CTO技术栈公众号