發(fā)布一個(gè)JavaScript工具類(lèi)庫(kù)jutil
由來(lái)
工作中jQuery用的比較多,但jQuery再?gòu)?qiáng)大也有些方法是沒(méi)有的,以前的做法就是東拼西湊,今天終于下定決心把平時(shí)用到的一些方法加以整理,這就是jutil的由來(lái)。
當(dāng)前只有17個(gè)方法,涉及到的有Array、HTML、Cookie & localStorage、Date、String。這些方法都采用了原生的JS,不依賴(lài)于jQuery。
都說(shuō)好的設(shè)計(jì)是易于理解的,不用過(guò)多介紹,而這也是我現(xiàn)在想達(dá)到的目標(biāo),因此下面的介紹會(huì)比較簡(jiǎn)單,如果大家哪個(gè)地方看不明白或有更好的建議,請(qǐng)?zhí)岢鰜?lái),我再優(yōu)化。
Array相關(guān)
jutil.arrayDistinct(Array)
jutil.arrayIndexOf(Array,Item)
實(shí)現(xiàn)代碼如下:
- arrayDistinct: function (arr) {
- var tempArr = {};
- for (var i = 0; i < arr.length; i++) {
- if (tempArr[arr[i] + 1]) {
- arr.splice(i, 1);
- i--;
- continue;
- }
- tempArr[arr[i] + 1] = true;
- }
- tempArr = null;
- return arr;
- },
- arrayIndexOf: function (arr, obj, iStart) {
- if (Array.prototype.indexOf) {
- return arr.indexOf(obj, (iStart || 0));
- }
- else {
- for (var i = (iStart || 0), j = arr.length; i < j; i++) {
- if (arr[i] === obj) {
- return i;
- }
- }
- return -1;
- }
- },
#p#
HTML相關(guān)
jutil.htmlEncode(sHtml)
jutil.htmlDecode(sHtml)
實(shí)現(xiàn)代碼如下:
- htmlEncode: function (sHtml) {
- var div = this.document.createElement("div"),
- text = this.document.createTextNode(sHtml);
- div.appendChild(text);
- return div.innerHTML;
- },
- htmlDecode: function (sHtml) {
- var div = this.document.createElement("div");
- div.innerHTML = sHtml;
- return div.innerText || div.textContent;
- },
如果有用jQuery,上面代碼可以進(jìn)一步簡(jiǎn)化為:
- htmlEncode: function (sHtml) {
- return $("div").text(sHtml).html();
- },
- htmlDecode: function (sHtml) {
- return $("div").html(sHtml).text();
- },
#p#
Cookie & localStorage相關(guān)
jutil.getCookie(sKey)
jutil.setCookie(sKey, sValue, iExpireSeconds)
jutil.deleteCookie(sKey)
jutil.getStorage(sKey)//如果瀏覽器支持HTML5本地存儲(chǔ)(localStorage)優(yōu)先用本地存儲(chǔ),否則用cookie,下同
jutil.setStorage(sKey, sValue, iExpireSeconds)
jutil.deleteStorage(sKey)
實(shí)現(xiàn)代碼如下:
- getCookie: function (sKey) {
- if (!sKey)
- return "";
- if (document.cookie.length > 0) {
- var startIndex = document.cookie.indexOf(sKey + "=")
- if (startIndex != -1) {
- startIndex = startIndex + sKey.length + 1
- var endIndex = document.cookie.indexOf(";", startIndex)
- if (endIndex == -1) {
- endIndex = document.cookie.length;
- }
- return decodeURIComponent(document.cookie.substring(startIndex, endIndex));
- }
- }
- return ""
- },
- setCookie: function (sKey, sValue, iExpireSeconds) {
- if (!sKey)
- return;
- var expireDate = new Date();
- expireDate.setTime(expireDate.getTime() + iExpireSeconds * 1000);
- this.document.cookie = sKey + "=" + encodeURIComponent(sValue) +
- ";expires=" + expireDate.toGMTString() + ";";
- },
- deleteCookie: function (sKey) {
- if (!sKey)
- return;
- this.document.cookie = sKey + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
- },
- getStorage: function (sKey) {
- if (!sKey)
- return;
- if (window.localStorage) {
- return decodeURIComponent(localStorage.getItem(sKey));
- }
- else {
- return this.getCookie(sKey);
- }
- },
- setStorage: function (sKey, sValue, iExpireSeconds) {
- if (!sKey)
- return;
- if (window.localStorage) {
- localStorage.setItem(sKey, encodeURIComponent(sValue));
- }
- else {
- this.setCookie(sKey, sValue, iExpireSeconds);
- }
- },
- deleteStorage: function (sKey) {
- if (!sKey)
- return;
- if (window.localStorage) {
- localStorage.removeItem(sKey);
- }
- else {
- this.deleteCookie(sKey);
- }
- },
#p#
Date相關(guān)
jutil.daysInFebruary(obj)//obj:數(shù)字(如2012)或時(shí)間(如new Date())
jutil.daysInYear(obj)//obj:數(shù)字(如2012)或時(shí)間(如new Date())
jutil.dateFormat(date, sFormat, sLanguage)//sFormat:yyyy為年,MM為月,DD為日,hh為時(shí),mm為分,ss為秒,MMM為月份,EEE為星期。sLanguage:默認(rèn)為中文,可以設(shè)置成英文(en)
jutil.dateDiff(biggerDate, smallerDate)
jutil.dateInterval(biggerDate, smallerDate)
從名子大家可能看不出最后兩個(gè)方法的區(qū)別,這里命名可能是有些問(wèn)題,大家有沒(méi)有推薦的?
dateDiff表示兩個(gè)時(shí)間之間相隔多長(zhǎng)時(shí)間,返回的是"10分鐘"、"2天"等字符串,一般用在要顯示"XX分鐘前"、"XX天前"時(shí)。
dateInterval表示兩個(gè)時(shí)間精確差(精確到秒),返回的是"1天:1小時(shí):1分鐘:1秒"這樣的字符串。
實(shí)現(xiàn)代碼如下:
- daysInFebruary: function (obj) {
- var year = 0;
- if (obj instanceof Date) {
- year = obj.getFullYear();
- }
- else if (typeof obj === "number") {
- year = obj;
- }
- else {
- return 0;
- }
- if (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) {
- return 29;
- }
- return 28;
- },
- daysInYear: function (obj) {
- var year = 0;
- if (obj instanceof Date) {
- year = obj.getFullYear();
- }
- else if (typeof obj === "number") {
- year = obj;
- }
- else {
- return 0;
- }
- if (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) {
- return 366;
- }
- return 365;
- },
- dateFormat: function (date, sFormat, sLanguage) {
- var time = {};
- time.Year = date.getFullYear();
- time.TYear = ("" + time.Year).substr(2);
- time.Month = date.getMonth() + 1;
- time.TMonth = time.Month < 10 ? "0" + time.Month : time.Month;
- time.Day = date.getDate();
- time.TDay = time.Day < 10 ? "0" + time.Day : time.Day;
- time.Hour = date.getHours();
- time.THour = time.Hour < 10 ? "0" + time.Hour : time.Hour;
- time.hour = time.Hour < 13 ? time.Hour : time.Hour - 12;
- time.Thour = time.hour < 10 ? "0" + time.hour : time.hour;
- time.Minute = date.getMinutes();
- time.TMinute = time.Minute < 10 ? "0" + time.Minute : time.Minute;
- time.Second = date.getSeconds();
- time.TSecond = time.Second < 10 ? "0" + time.Second : time.Second;
- time.Millisecond = date.getMilliseconds();
- time.Week = date.getDay();
- var MMMArrEn = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
- MMMArr = ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
- WeekArrEn = ["Sun", "Mon", "Tue", "Web", "Thu", "Fri", "Sat"],
- WeekArr = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
- oNumber = time.Millisecond / 1000;
- if (sFormat != undefined && sFormat.replace(/\s/g, "").length > 0) {
- if (sLanguage != undefined && sLanguage === "en") {
- MMMArr = MMMArrEn.slice(0);
- WeekArr = WeekArrEn.slice(0);
- }
- sFormat = sFormat.replace(/yyyy/ig, time.Year)
- .replace(/yyy/ig, time.Year)
- .replace(/yy/ig, time.TYear)
- .replace(/y/ig, time.TYear)
- .replace(/MMM/g, MMMArr[time.Month - 1])
- .replace(/MM/g, time.TMonth)
- .replace(/M/g, time.Month)
- .replace(/dd/ig, time.TDay)
- .replace(/d/ig, time.Day)
- .replace(/HH/g, time.THour)
- .replace(/H/g, time.Hour)
- .replace(/hh/g, time.Thour)
- .replace(/h/g, time.hour)
- .replace(/mm/g, time.TMinute)
- .replace(/m/g, time.Minute)
- .replace(/ss/ig, time.TSecond)
- .replace(/s/ig, time.Second)
- .replace(/fff/ig, time.Millisecond)
- .replace(/ff/ig, oNumber.toFixed(2) * 100)
- .replace(/f/ig, oNumber.toFixed(1) * 10)
- .replace(/EEE/g, WeekArr[time.Week]);
- }
- else {
- sFormat = time.Year + "-" + time.Month + "-" + time.Day + " " + time.Hour + ":" + time.Minute + ":" + time.Second;
- }
- return sFormat;
- },
- dateDiff: function (biggerDate, smallerDate) {
- var intervalSeconds = parseInt((biggerDate - smallerDate) / 1000);
- if (intervalSeconds < 60) {
- return intervalSeconds + "秒";
- }
- else if (intervalSeconds < 60 * 60) {
- return Math.floor(intervalSeconds / 60) + "分鐘";
- }
- else if (intervalSeconds < 60 * 60 * 24) {
- return Math.floor(intervalSeconds / (60 * 60)) + "小時(shí)";
- }
- else if (intervalSeconds < 60 * 60 * 24 * 7) {
- return Math.floor(intervalSeconds / (60 * 60 * 24)) + "天";
- }
- else if (intervalSeconds < 60 * 60 * 24 * 31) {
- return Math.floor(intervalSeconds / (60 * 60 * 24 * 7)) + "周";
- }
- else if (intervalSeconds < 60 * 60 * 24 * 365) {
- return Math.floor(intervalSeconds / (60 * 60 * 24 * 30)) + "月";
- }
- else if (intervalSeconds < 60 * 60 * 24 * 365 * 1000) {
- return Math.floor(intervalSeconds / (60 * 60 * 24 * 365)) + "年";
- }
- else {
- return Math.floor(intervalSeconds / (60 * 60 * 24)) + "天";
- }
- },
- dateInterval: function (biggerDate, smallerDate) {
- var intervalSeconds = parseInt((biggerDate - smallerDate) / 1000),
- day = Math.floor(intervalSeconds / (60 * 60 * 24)),
- hour = Math.floor((intervalSeconds - day * 24 * 60 * 60) / 3600),
- minute = Math.floor((intervalSeconds - day * 24 * 60 * 60 - hour * 3600) / 60),
- second = Math.floor(intervalSeconds - day * 24 * 60 * 60 - hour * 3600 - minute * 60);
- return day + "天:" + hour + "小時(shí):" + minute + "分鐘:" + second + "秒";
- },
#p#
String相關(guān)
jutil.replaceURLWithHTMLLinks(sText, bBlank)
jutil.getLength(sVal, bChineseDouble)
這個(gè)就比較簡(jiǎn)單了,直接上代碼:
- replaceURLWithHTMLLinks: function (sText, bBlank) {
- var pattern = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
- if (bBlank) {
- sText = sText.replace(pattern, "<a target='_blank' href='$1'>$1</a>");
- }
- else {
- sText = sText.replace(pattern, "<a href='$1'>$1</a>");
- }
- return sText;
- },
- getLength: function (sVal, bChineseDouble) {
- var chineseRegex = /[\u4e00-\u9fa5]/g;
- if (bChineseDouble != undefined && bChineseDouble === false) {
- return sVal.length;
- }
- else {
- if (chineseRegex.test(sVal)) {
- return sVal.replace(chineseRegex, "zz").length;
- }
- return sVal.length;
- }
- }
測(cè)試代碼
測(cè)試效果:
小結(jié)
后面會(huì)繼續(xù)添加正則方面的內(nèi)容,本文也會(huì)持續(xù)更新。目前JS下載鏈接:http://files.cnblogs.com/artwl/jutil.js
原文鏈接:http://www.cnblogs.com/artwl/archive/2012/07/09/2583114.html