Last active
August 29, 2015 13:58
-
-
Save pekrockstar/9978470 to your computer and use it in GitHub Desktop.
Some common functions for javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
*@fileOverview JavaScript utils | |
*@author ra <[email protected]> | |
*@version 0.0.1 | |
*@see {@link http://usejsdoc.org|jsdoc} | |
*@example | |
* | |
* var currency=comm.formatCurrency(123456); | |
* //output | |
* '123, 456.00' | |
* | |
* var now=comm.date2String(); | |
* ... | |
* | |
*/ | |
/** @namespace comm */ | |
(function(exports){ | |
/* | |
* Restore formatted currency | |
* @param {String} num | |
* @return {Number} num | |
*/ | |
exports.restoreCurrency=function(num){ | |
var num1=num.replace(',','').replace(/,/g,''); | |
return num1; | |
}; | |
/** | |
* Get a string length | |
* <p><b>provide to zh_CN area</b></p> | |
* @param str | |
* @returns {Number} | |
*/ | |
exports.getLen=function(str) { | |
var totalLength = 0; | |
var list = str.split(""); | |
for(var i = 0; i < list.length; i++) { | |
var s = list[i]; | |
if (s.match(/[\u0000-\u00ff]/g)) { //half-width | |
totalLength += 1; | |
} else if (s.match(/[\u4e00-\u9fa5]/g)) { //chinese | |
totalLength += 2; | |
} else if (s.match(/[\uff00-\uffff]/g)) { //full-width | |
totalLength +=2; | |
}else{ | |
totalLength=0; | |
} | |
} | |
return totalLength; | |
}; | |
/** | |
* Close current window(browser only) | |
*/ | |
exports.close=function(){ | |
if(!this.isWindow){ | |
return; | |
} | |
if (navigator.userAgent.indexOf("MSIE") > 0) { | |
if (navigator.userAgent.indexOf("MSIE 6.0") > 0) { | |
window.opener = null; | |
window.close(); | |
} else { | |
window.open('', '_top'); | |
window.top.close(); | |
} | |
} else if (navigator.userAgent.indexOf("Firefox") > 0) { | |
window.location.href = 'about:blank '; | |
} else { | |
window.opener = null; | |
window.open('', '_self', ''); | |
window.close(); | |
} | |
}; | |
/** | |
* Go back page | |
* @param {Number} cnt page num | |
*/ | |
exports.goBack=function(cnt){ | |
if(!this.isWindow){ | |
return; | |
} | |
if(undefined == cnt || isNaN(parseInt(cnt,10))){ | |
history.go(-1); | |
}else{ | |
history.go(0-parseInt(cnt,10)); | |
} | |
}; | |
/** | |
* Check if "undifined, null, " contains. | |
* @param {Object} src | |
* @return {Boolean} true if found. | |
*/ | |
exports.isBlank=function(src){ | |
src =this.trim(src); | |
if(src == undefined || src=="null" || src===""){ | |
return true; | |
}else{ | |
return false; | |
} | |
}; | |
/** | |
* Get bytes | |
* @param {String} str | |
* @return {Array} bytes | |
*/ | |
exports.bin=function(str){ | |
var bytes=[]; | |
for(var i=0;i<str.length;i++){ | |
bytes.push(str.charCodeAt(i)); | |
} | |
return bytes; | |
}; | |
/** | |
* Get enumeration value | |
* @example | |
* // Enums_LOCALE="en:en_US;zh:zh_CN;"; | |
* var locale=getEnumValue("Enums_LOCALE", "en"); // return en_US | |
* @param {Object} enums | |
* @param {Object} key | |
* @return {String} value | |
*/ | |
exports.getEnumValue=function(enums,key){ | |
if(typeof enums === 'undefined'){ | |
return ""; | |
} | |
var idx1 = enums.indexOf(key); | |
var idx2 = enums.indexOf(":",idx1); | |
var idx3 = enums.indexOf(";",idx2); | |
if(-1==idx1 || -1==idx2 || -1==idx3){ | |
return ""; | |
}else{ | |
return enums.substring(idx2+1,idx3); | |
} | |
}; | |
/** | |
* Removes all newlines, | |
* spaces (including non-breaking spaces), and tabs from the beginning and end of the supplied string | |
* @param {String} str | |
* @return {String} | |
*/ | |
exports.trim=function(str) | |
{ | |
if (typeof str === 'string') return str.replace(/(^\s*)|(\s*$)/g, ''); | |
}; | |
/** | |
* Removes all newlines, | |
* spaces (including non-breaking spaces), and tabs from the beginning of the supplied string | |
* @param {String} str | |
* @return {String} | |
*/ | |
exports.trimBegin=function(str) | |
{ | |
if (typeof str == 'string') return str.replace(/(^\s*)/g, ''); | |
}; | |
/** | |
* Removes all newlines, | |
* spaces (including non-breaking spaces), and tabs from the end of the supplied string | |
* @param {String} str | |
* @return {String} | |
*/ | |
exports.trimEnd=function(str) | |
{ | |
if (typeof str == 'string') return str.replace(/(\s*$)/g, ''); | |
}; | |
/** | |
* Read cookie by name | |
* @param {String} c_name cookie name | |
* @return {String} cookie value | |
*/ | |
exports.readCookie=function(c_name) { | |
if(!this.isWindow){ | |
return; | |
} | |
if (document.cookie.length > 0) { | |
c_start = document.cookie.indexOf(c_name + "="); | |
if (c_start != -1) { | |
c_start = c_start + c_name.length + 1; | |
c_end = document.cookie.indexOf(";", c_start); | |
if (c_end == -1) | |
c_end = document.cookie.length; | |
return unescape(document.cookie.substring(c_start, c_end)); | |
} | |
} | |
return ""; | |
}; | |
/** | |
* Write cookie | |
* @param {String} c_name cookie name | |
* @param {String} value cookie value | |
* @parm {Number} expiredays expire days | |
*/ | |
exports.writeCookie=function(c_name, value, expiredays) { | |
if(!this.isWindow){ | |
return ""; | |
} | |
var exdate = new Date(); | |
exdate.setDate(exdate.getDate() + expiredays); | |
document.cookie = c_name + "=" + escape(value)+(expiredays ==undefined?"":";expires=" + exdate.toGMTString()); | |
}; | |
/** | |
* Check leap year | |
* @param {Date} date | |
* @return {Boolean} true if yes | |
*/ | |
exports.isLeapYear=function(date){ | |
if(date == undefined){ | |
date=new Date(); | |
} | |
return (0===date.getYear()%4&&((date.getYear()%100!==0)||(date.getYear()%400===0))); | |
}; | |
/** | |
* Date to formatted stringyy | |
* @param {Date} date default is current date, if you not set | |
* @param {String} pattern | |
* <ul> | |
* <li>YYYY/yyyy/YY/yy years</li> | |
* <li>MM/m months</li> | |
* <li>W/w weeks</li> | |
* <li>DD/dd/D/d days</li> | |
* <li>HH/hh/H/h hours</li> | |
* <li>mm/m minutes</li> | |
* <li>SS/ss/S/s second</li> | |
* </ul> | |
* @return {String} formatted date. | |
*/ | |
exports.date2String=function(date, pattern){ | |
if(date == undefined){ | |
date=new Date(); | |
} | |
if(this.isBlank(pattern)){ | |
pattern="yyyy-MM-dd HH:mm:ss"; | |
} | |
var week = ['Sun','Mon','Tue','Wed','Thur','Fri','Sat']; | |
var str=pattern; | |
str=str.replace(/yyyy|YYYY/,date.getFullYear()); | |
str=str.replace(/yy|YY/,(date.getYear() % 100)>9?(date.getYear() % 100).toString():'0' + (date.getYear() % 100)); | |
str=str.replace(/MM/,date.getMonth()>9?(date.getMonth() + 1):'0' + (date.getMonth() + 1)); | |
str=str.replace(/M/g,date.getMonth()); | |
str=str.replace(/w|W/g,week[date.getDay()]); | |
str=str.replace(/dd|DD/,date.getDate()>9?date.getDate().toString():'0' + date.getDate()); | |
str=str.replace(/d|D/g,date.getDate()); | |
str=str.replace(/hh|HH/,date.getHours()>9?date.getHours().toString():'0' + date.getHours()); | |
str=str.replace(/h|H/g,date.getHours()); | |
str=str.replace(/mm/,date.getMinutes()>9?date.getMinutes().toString():'0' + date.getMinutes()); | |
str=str.replace(/m/g,date.getMinutes()); | |
str=str.replace(/ss|SS/,date.getSeconds()>9?date.getSeconds().toString():'0' + date.getSeconds()); | |
str=str.replace(/s|S/g,date.getSeconds()); | |
return str; | |
}; | |
/** | |
* Date change | |
* @param {String} leve | |
* <ul> | |
* <li>y year</li> | |
* <li>m month</li> | |
* <li>d day</li> | |
* <li>w week</li> | |
* <li>h hour</li> | |
* <li>mi minute</li> | |
* <li>s seconds</li> | |
* </ul> | |
* @num {Number} num "+" means add, "-" meas sub | |
* @date {Date} date | |
* @return {Date} modified date. | |
*/ | |
exports.dateAdd=function(level, num, date){ | |
if(date == undefined){ | |
date = new Date(); | |
} | |
switch (level) { | |
case 's' :return new Date(date.getTime() + (1000 * num)); | |
case 'mi' :return new Date(date.getTime() + (60000 * num)); | |
case 'h' :return new Date(date.getTime() + (3600000 * num)); | |
case 'w' :return new Date(date.getTime() + ((86400000 * 7) * num)); | |
case 'd' :return new Date(date.getTime() + (86400000 * num)); | |
case 'm' :return new Date(date.getFullYear(), (date.getMonth()) + num, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()); | |
case 'y' :return new Date((date.getFullYear() + num), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()); | |
} | |
}; | |
/** | |
* Diff date | |
* @param {String} level | |
* <ul> | |
* <li>y year</li> | |
* <li>m month</li> | |
* <li>d day</li> | |
* <li>w week</li> | |
* <li>h hour</li> | |
* <li>mi minute</li> | |
* <li>s seconds</li> | |
* </ul> | |
* @date {Date} dateBegin | |
* @date {Date} dateEnd | |
* @return {Number} time differences | |
* | |
* */ | |
exports.dateDiff=function(level,dateBegin, dtEnd) { | |
switch (level) { | |
case 's' :return parseInt((dtEnd - dateBegin) / 1000); | |
case 'mi' :return parseInt((dtEnd - dateBegin) / 60000); | |
case 'd' :return parseInt((dtEnd - dateBegin) / 86400000); | |
case 'h' :return parseInt((dtEnd - dateBegin) / 3600000); | |
case 'w' :return parseInt((dtEnd - dateBegin) / (86400000 * 7)); | |
case 'm' :return (dtEnd.getMonth()+1)+((dtEnd.getFullYear()-dateBegin.getFullYear())*12) - (dateBegin.getMonth()+1); | |
case 'y' :return dtEnd.getFullYear() - dateBegin.getFullYear(); | |
} | |
}; | |
/** | |
* Get max day of a month | |
* @param {String} year | |
* @param {String} month | |
* @return {Number} max day | |
*/ | |
exports.getMaxDay=function(year,month) { | |
if(month==4||month==6||month==9||month==11){ | |
return 30; | |
} | |
if(month==2){ | |
if(year%4===0&&year%100!==0 || year%400===0){ | |
return "29"; | |
} | |
else{ | |
return "28"; | |
} | |
} | |
else{ | |
return "31"; | |
} | |
}; | |
/** | |
* Formatting currency | |
* @param {Number} num | |
* @return {String} formatted currencies. | |
**/ | |
exports.formatCurrency=function(num) { | |
num = num.toString().replace(/\$|\,/g,''); | |
if(isNaN(num)) | |
num = "0"; | |
var sign = (num == (num = Math.abs(num))); | |
num = Math.floor(num*100+0.50000000001); | |
var cents = num%100; | |
num = Math.floor(num/100).toString(); | |
if(cents<10) | |
cents = "0" + cents; | |
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) | |
num = num.substring(0,num.length-(4*i+3))+','+ | |
num.substring(num.length-(4*i+3)); | |
return (((sign)?'':'-') + num + '.' + cents); | |
}; | |
/** | |
* Get phone number type | |
* <p>For china:</p> | |
* <ul> | |
* <li>0 unknow</li> | |
* <li>1 china mobile (cellphone)</li> | |
* <li>2 china unicom (cellphone)</li> | |
* <li>3 china net (cellphone)</li> | |
* <li>4 china net (telphone)</li> | |
* </ul> | |
* @param {String} num number | |
* @return {Number} number type | |
*/ | |
exports.getPhoneNuType=function(num){ | |
var _cm = /^(((13[5-9])|(147)|(15[012789])|(18[23478]))\d{8})|(134[0-8])\d{7}$/; | |
var _cu = /^((13[0-2])|(145)|(15[5-6])|(18[5-6]))\d{8}$/; | |
var _ct = /^(((133)|(153)|(18[019]))\d{8})|(1349)\d{7}$/; | |
var _tel= /^((0[12]\d{1}\d{8})|(0[3-9]\d{2}\d{7,8}))$/; | |
if(_cm.test(num)){ | |
return 1; | |
}else if(_cu.test(num)){ | |
return 2; | |
}else if(_ct.test(num)){ | |
return 3; | |
}else if(_tel.test(num)){ | |
return 4; | |
}else{ | |
return 0; | |
} | |
}; | |
/** | |
* | |
* Check browser env? | |
*@return {Boolean} true if has browser env | |
*/ | |
exports.isWindow=typeof window === 'undefined'?false:true; | |
})(typeof exports === 'undefined'?this.comm={}:exports); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment