JavaScript 自定义函数库

javascript function library


相关信息

# redactor time comment
1 moses.mo 2016.6.12 create
2 moses.mo 2016.6.14 modify

函数库列表

# function
1 isEmpty
2 isDate
3 isTelephone
4 isMobile
5 isEmail
6 isIDCard
7 isNumber
8 isMoney
9 isDecimal
10 isPost
11 isURL
12 isValidUserName
13 isValidReg
14 isValidLength
15 strReverse
16 strCut
17 getHost
18 getHost
19 checkUrlState
20 htmlEncode
21 htmlDecode
22 setCookie
23 getCookie
24 addFavorite
25 ip2int
26 int2ip
27 getPageHeight
28 getPageWidth
29 getViewSize
30 getPageScrollLeft
31 getPageScrollTop
32 back2Top
33 openWindow
34 ltrim
35 rtrim
36 trim
37 toDBC
38 toCDB
39 base64encode
40 base64encode
41 utf16to8
42 utf8to16
43 encodeUTF8
44 decodeUTF8
45 accAdd
46 accSub
47 accSub
48 accDiv
49 horCenter
50 verCenter
51 convertFullPathName
52 startWith
53 endWith
54 help

源代码

/*
 * [ javascript function library ]  
 *@Auhor      [ moses.mo ]      
 *@Email      [ [email protected] ]
 *@Requires  [ jquery ] 
 *@Link      [ http://blog.csdn.net/mosesmo1989/ ]
 *-----------------------------------------------------------------
 *| #   |   redactor      |    time        |    comment            |
 *|  1  |   moses.mo      |  2016.6.12     |    create             |
 *|  2  |   moses.mo      |  2016.6.14     |    modify             |
 *-----------------------------------------------------------------
 */

define(["jquery"], function($) {
    'use strict';

    var js_cmn = (function() {
        //javascript function library message
        var auhor = 'moses.mo',
                version = 'v1.1.0',
                lastTime = '2016.6.14';


        /*
         * [ check content if empty | undefined, null, '', false, 0, [], {} return true ]
         * @content {string} input value
         * @return {boolean} true | false
         */
        var isEmpty = function(content) {
            switch (typeof content) {
                case 'undefined':
                    return true;
                case 'string':
                    if (trim(content).length == 0)
                        return true;
                    break;
                case 'boolean':
                    if (!content)
                        return true;
                    break;
                case 'number':
                    if (0 === content)
                        return true;
                    break;
                case 'object':
                    if (null === content)
                        return true;
                    if (undefined !== content.length && content.length == 0)
                        return true;
                    for (var k in content) {
                        return false;
                    }
                    return true;
                    break;
            }
            return false;
        };

        /*
         * [ check content if date ]
         * @content {string} input value
         * @return {boolean} true | false
         */
        var isDate = function(content) {
            var result = content.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
            if (isEmpty(content))
                return false;
            var d = new Date(result[1], result[3] - 1, result[4]);
            if ((d.getFullYear() == result[1] && (d.getMonth() + 1) == result[3] && d.getDate() == result[4])) {
                return true;
            }
            return false;
        };

        /*
         * [ check content if fixed-line telephone ]
         * @content {string} input value
         * @return {boolean} true | false
         */
        var isTelephone = function(content) {
            var phone_reg = new RegExp(/^([+]{0,1}\d{3,4}|\d{3,4}-)?\d{7,8}$/);
            if (!phone_reg.test(content) || isEmpty(content))
                return false;
            return true;
        };

        /*
         * [ check content if Mobile ]
         * @content {string} input value
         * @return {boolean} true | false
         */
        var isMobile = function(content) {
            var mobile_reg = new RegExp(/^0{0,1}1[0-9]{10}$/);
            if (!mobile_reg.test(content) || isEmpty(content))
                return false;
            return true;
        };

        /*
         * [ check content if Email ]
         * @content {string} input value
         * @return {boolean} true | false
         */
        var isEmail = function(content) {
            var re = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
            if (re.test(content) != true || isEmpty(content))
                return false;
            else
                return true;
        };

        /*
         * [ check content if ID card ]
         * @content {string} input value
         * @return {boolean} true | false
         */
        var isIDCard = function(content) {
            var IDCardReg = new RegExp(/(^\d{15}$)|(^\d{17}([0-9]|X)$)/);
            if (!IDCardReg.test(content) || isEmpty(content))
                return false;
            return true;
        };

        /*
         * [ check content if Number ]
         * @content {string} input value
         * @return {boolean} true | false
         */
        var isNumber = function(content) {
            var patrn = /^\d*$/;
            if (patrn.exec(content) == null || isEmpty(content))
                return false;
            else
                return true;
        };

        /*
         * [ check content if Money ]
         * @content {string} input value
         * @return {boolean} true | false
         */
        var isMoney = function(content) {
            var patrn = /^(([1-9]\d+|0)\.\d{2}|([1-9]\d+|0))$/;
            if (patrn.exec(content) == null || isEmpty(content))
                return false;
            else
                return true;
        };

        /*
         * [ check content if Decimal ]
         * @content {string} input value
         * @return {boolean} true | false
         */
        var isDecimal = function(content) {
            var patrn = /^\d*\.?\d{1,2}$/;
            if (patrn.exec(content) == null || isEmpty(content))
                return false;
            else
                return true;
        };

        /*
         * [ check content if post ]
         * @content {string} input value
         * @return {boolean} true | false
         */
        var isPost = function(content) {
            var re = /^[1-9]\d{5}(?!\d)/;
            if (content.match(re) == null || isEmpty(content))
                return false;
            else
                return true;
        };

        /*
         * [ check content if URL ]
         * @content {string} input value
         * @return {boolean} true | false
         */
        var isURL = function(content) {
            var regular = /^\b(((https?|ftp):\/\/)?[-a-z0-9]+(\.[-a-z0-9]+)*\.(?:com|edu|gov|int|mil|net|org|biz|info|name|museum|asia|coop|aero|[a-z][a-z]|((25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]\d)|\d))\b(\/[-a-z0-9_:\@&?=+,.!\/~%\$]*)?)$/i;
            //var regular=/^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/)(\S+\.\S+)$/; 
            if (isEmpty(content))
                return false;
            if (regular.test(content))
                return true;
            else
                return false;
        };

        /*
         * [ check content if valid username | English, letters, Numbers, underscore, underline not at the beginning or end ]
         * @content {string} input value
         * @return {boolean} true | false
         */
        var isValidUserName = function(content) {
            var re = /^(?!_)(?!.*?_$)(\w|[\u4E00-\u9FA5])*$/;
            if (content.match(re) == null || isEmpty(content))
                return false;
            else
                return true;
        };

        /*
         * [ check content if Valid character ]
         * @content {string} input value
         * @return {boolean} true | false
         */
        var isValidReg = function(content) {
            var re = /<|>|\[|\]|\{|\}|『|』|※|○|●|◎|§|△|▲|☆|★|◇|◆|□|▼|㊣|﹋|⊕|⊙|〒|ㄅ|ㄆ|ㄇ|ㄈ|ㄉ|ㄊ|ㄋ|ㄌ|ㄍ|ㄎ|ㄏ|ㄐ|ㄑ|ㄒ|ㄓ|ㄔ|ㄕ|ㄖ|ㄗ|ㄘ|ㄙ|ㄚ|ㄛ|ㄜ|ㄝ|ㄞ|ㄟ|ㄢ|ㄣ|ㄤ|ㄥ|ㄦ|ㄧ|ㄨ|ㄩ|■|▄|▆|\*|@|#|\^|\\/;
            if (re.test(content) == true || isEmpty(content))
                return false;
            else
                return true;
        };

        /*
         * [ check content if Valid length ]
         * @content {string} input value
         * @len {integer} effective length of the data
         * @return {boolean} true | false
         */
        var isValidLength = function(content, len) {
            if (content.length < len || isEmpty(content))
                return false;
            return true;
        };

        /*
         * [ string reverse ]
         * @content {string} input value
         * @return {string} the string after reverse
         */
        var strReverse = function(content) {
            return content.split('').reverse().join('');
        };

        /*
         * [ cut a too long string ]
         * @str {string} input value
         * @len {integer} length of the need to cut
         * @return {string} the string after cut
         */
        var strCut = function(str, len) {
            var temp;
            var icount = 0;
            var patrn = /[^\x00-\xff]/;
            var strre = "";
            for (var i = 0; i < str.length; i++) {
                if (icount < len - 1) {
                    temp = str.substr(i, 1);
                    if (patrn.exec(temp) == null)
                        icount = icount + 1;
                    else
                        icount = icount + 2;
                    strre += temp;
                } else {
                    break
                }
            }
            return strre + "...";
        };

        /*
         * [ access to domain name host ]
         * @url {string} URL
         * @return {string} domain name host
         */
        var getHost = function(url) {
            var host = "null";
            if (typeof url == "undefined" || null == url) {
                url = window.location.href;
            }
            var regex = /^\w+\:\/\/([^\/]*).*/;
            var match = url.match(regex);
            if (typeof match != "undefined" && null != match) {
                host = match[1];
            }
            return host;
        };

        /*
         * [ get the URL ]
         * @return {string} URL
         */
        var getURL = function() {
            var currentPageUrl = "";
            if (typeof this.href === "undefined") {
                currentPageUrl = document.location.toString().toLowerCase();
            }
            else {
                currentPageUrl = this.href.toString().toLowerCase();
            }
            return currentPageUrl;
        };

        /*
         * [ check URL State ]
         * @url {string} URL
         * @return {boolean} true | false
         */
        var checkUrlState = function(url) {
            var xmlhttp = new ActiveXObject("microsoft.xmlhttp");
            xmlhttp.Open("GET", url, false);
            try {
                xmlhttp.Send();
            } catch (e) {
            } finally {
                var result = xmlhttp.responseText;
                if (result) {
                    if (xmlhttp.Status == 200) {
                        return(true);
                    } else {
                        return(false);
                    }
                } else {
                    return(false);
                }
            }
        };

        /*
         * [ transfer the HTML label ]
         * @content {string} URL
         * @return {string} html after encode
         */
        var htmlEncode = function(content) {
            return content.replace(/&/g, '&').replace(/\"/g, '"').replace(/, '<').replace(/>/g, '>');
        };

        /*
         * [ restore the HTML label ]
         * @content {string} URL
         * @return {string} html after restore
         */
        var htmlDecode = function(content) {
            return content.replace(/&/g, '&').replace(/"/g, '\"').replace(/, '<').replace(/>/g, '>');
        };

        /*
         * [ set cookie value ]
         * @key {string} cookie key
         * @value {string} cookie value
         * @hours {integer} set hours
         * @return {} no return
         */
        var setCookie = function(key, value, hours) {
            var d = new Date();
            var offset = 8;
            var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
            var nd = utc + (3600000 * offset);
            var exp = new Date(nd);
            exp.setTime(exp.getTime() + hours * 60 * 60 * 1000);
            document.cookie = key + "=" + escape(value) + ";path=/;expires=" + exp.toGMTString() + ";domain=360doc.com;";
        };

        /*
         * [ get cookie value ]
         * @key {string} cookie key
         * @return {string} cookie value
         */
        var getCookie = function(key) {
            var arr = document.cookie.match(new RegExp("(^| )" + key + "=([^;]*)(;|$)"));
            if (arr != null)
                return unescape(arr[2]);
            return null;
        };

        /*
         * [ add to favorite ]
         * @url {string} favorite url
         * @title {string} favorite title
         * @return {boolen} true | false
         */
        var addFavorite = function(url, title) {
            try {
                window.external.addFavorite(url, title);
            } catch (e) {
                try {
                    window.sidebar.addPanel(title, url, "");
                    return true;
                } catch (e) {
                    return false;
                }
            }
        };

        /*
         * [ IP to int ]
         * @ip {string} ip
         * @return {integer} integer
         */
        var ip2int = function(ip) {
            var num = 0;
            ip = ip.split(".");
            num = Number(ip[0]) * 256 * 256 * 256 + Number(ip[1]) * 256 * 256 + Number(ip[2]) * 256 + Number(ip[3]);
            num = num >>> 0;
            return num;
        };

        /*
         * [ int to IP ]
         * @num {integer} integer
         * @return {string} ip
         */
        var int2ip = function(num) {
            var str;
            var tt = new Array();
            tt[0] = (num >>> 24) >>> 0;
            tt[1] = ((num << 8) >>> 24) >>> 0;
            tt[2] = (num << 16) >>> 24;
            tt[3] = (num << 24) >>> 24;
            str = String(tt[0]) + "." + String(tt[1]) + "." + String(tt[2]) + "." + String(tt[3]);
            return str;
        };

        /*
         * [ get page height ]
         * @return {integer} page height
         */
        var getPageHeight = function() {
            var g = document,
                    a = g.body,
                    f = g.documentElement,
                    d = g.compatMode == "BackCompat" ? a : g.documentElement;
            return Math.max(f.scrollHeight, a.scrollHeight, d.clientHeight);
        };

        /*
         * [ get page width ]
         * @return {integer} page width
         */
        var getPageWidth = function() {
            var g = document,
                    a = g.body,
                    f = g.documentElement,
                    d = g.compatMode == "BackCompat" ? a : g.documentElement;
            return Math.max(f.scrollWidth, a.scrollWidth, d.clientWidth);
        };

        /*
         * [ get page view Size ]
         * @return {array} page view size x & y
         */
        var getViewSize = function() {
            var de = document.documentElement;
            var db = document.body;
            var viewW = de.clientWidth == 0 ? db.clientWidth : de.clientWidth;
            var viewH = de.clientHeight == 0 ? db.clientHeight : de.clientHeight;
            return Array(viewW, viewH);
        };

        /*
         * [ get page scroll left ]
         * @return {integer} page scroll left
         */
        var getPageScrollLeft = function() {
            var a = document;
            return a.documentElement.scrollLeft || a.body.scrollLeft;
        };

        /*
         * [ get page scroll top ]
         * @return {integer} page scroll top
         */
        var getPageScrollTop = function() {
            var a = document;
            return a.documentElement.scrollTop || a.body.scrollTop;
        };

        /*
         * [ go back to top ]
         * btnId {string} button ID
         * @return {} no return
         */
        var back2Top = function(btnId) {
            var btn = document.getElementById(btnId);
            var d = document.documentElement;
            var b = document.body;
            window.onscroll = set;
            btn.style.display = "none";
            btn.onclick = function() {
                btn.style.display = "none";
                window.onscroll = null;
                this.timer = setInterval(function() {
                    d.scrollTop -= Math.ceil((d.scrollTop + b.scrollTop) * 0.1);
                    b.scrollTop -= Math.ceil((d.scrollTop + b.scrollTop) * 0.1);
                    if ((d.scrollTop + b.scrollTop) == 0)
                        clearInterval(btn.timer, window.onscroll = set);
                }, 10);
            };
            function set() {
                btn.style.display = (d.scrollTop + b.scrollTop > 100) ? 'block' : "none";
            }
        };

        /*
         * [ open a new window ]
         * @url {string} URL
         * @windowName {string} window name
         * @width {integer} width
         * @height {integer} height
         * @return {} no return
         */
        var openWindow = function(url, windowName, width, height) {
            var x = parseInt(screen.width / 2.0) - (width / 2.0);
            var y = parseInt(screen.height / 2.0) - (height / 2.0);
            var isMSIE = (navigator.appName == "Microsoft Internet Explorer");
            if (isMSIE) {
                var p = "resizable=1,location=no,scrollbars=no,width=";
                p = p + width + ",height=" + height + ",left=" + x + ",top=" + y;
                retval = window.open(url, windowName, p);
            } else {
                var win = window.open(url, "ZyiisPopup", "top=" + y + ",left=" + x + ",scrollbars=" + scrollbars + ",dialog=yes,modal=yes,width=" + width + ",height=" + height + ",resizable=no");
                eval("try { win.resizeTo(width, height); } catch(e) { }");
                win.focus();
            }
        };

        /*
         * [ clear left blank ]
         * @str {string} string
         * @return {string} string after clear left blank
         */
        var ltrim = function(str) {
            return str.replace(/^(\s*| *)/, "");
        };

        /*
         * [ clear right blank ]
         * @str {string} string
         * @return {string} string after clear right blank
         */
        var rtrim = function(str) {
            return str.replace(/(\s*| *)$/, "");
        };

        /*
         * [ clear both sides blank ]
         * @str {string} string
         * @return {string} string after clear both sides blank
         */
        var trim = function(str) {
            return str.replace(/(^\s*)|(\s*$)/g, "");
        };

        /*
         * [ Half Angle into whole Angle ]
         * @str {string} Half Angle string
         * @return {string} whole Angle string
         */
        var toDBC = function(str) {
            var result = '',
                    code = '';
            for (var i = 0; i < str.length; i++) {
                code = str.charCodeAt(i);
                if (code >= 33 && code <= 126) {
                    result += String.fromCharCode(str.charCodeAt(i) + 65248);
                } else if (code == 32) {
                    result += String.fromCharCode(str.charCodeAt(i) + 12288 - 32);
                } else {
                    result += str.charAt(i);
                }
            }
            return result;
        };

        /*
         * [ whole Angle into Half Angle ]
         * @str {string} whole Angle string
         * @return {string} Half Angle string
         */
        var toCDB = function(str) {
            var result = '',
                    code = '';
            for (var i = 0; i < str.length; i++) {
                code = str.charCodeAt(i);
                if (code >= 65281 && code <= 65374) {
                    result += String.fromCharCode(str.charCodeAt(i) - 65248);
                } else if (code == 12288) {
                    result += String.fromCharCode(str.charCodeAt(i) - 12288 + 32);
                } else {
                    result += str.charAt(i);
                }
            }
            return result;
        };

        /*
         * [ base64 encode ]
         * @str {string} string
         * @return {string} string after base64 encode
         */
        var base64encode = function(str) {
            var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
            var out, i, len;
            var c1, c2, c3;
            len = str.length;
            i = 0;
            out = "";
            while (i < len) {
                c1 = str.charCodeAt(i++) & 0xff;
                if (i == len) {
                    out += base64EncodeChars.charAt(c1 >> 2);
                    out += base64EncodeChars.charAt((c1 & 0x3) << 4);
                    out += "==";
                    break;
                }
                c2 = str.charCodeAt(i++);
                if (i == len) {
                    out += base64EncodeChars.charAt(c1 >> 2);
                    out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
                    out += base64EncodeChars.charAt((c2 & 0xF) << 2);
                    out += "=";
                    break;
                }
                c3 = str.charCodeAt(i++);
                out += base64EncodeChars.charAt(c1 >> 2);
                out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
                out += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
                out += base64EncodeChars.charAt(c3 & 0x3F);
            }
            return out;
        };

        /*
         * [ base64 decode ]
         * @str {string} string
         * @return {string} string after base64 decode
         */
        var base64decode = function(str) {
            var base64DecodeChars = new Array(-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
                    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1,
                    -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7,
                    8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
                    29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1);
            var c1, c2, c3, c4;
            var i, len, out;
            len = str.length;
            i = 0;
            out = "";
            while (i < len) {
                /* c1 */
                do {
                    c1 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
                }
                while (i < len && c1 == -1);
                if (c1 == -1)
                    break;
                /* c2 */
                do {
                    c2 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
                }
                while (i < len && c2 == -1);
                if (c2 == -1)
                    break;
                out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));
                /* c3 */
                do {
                    c3 = str.charCodeAt(i++) & 0xff;
                    if (c3 == 61)
                        return out;
                    c3 = base64DecodeChars[c3];
                }
                while (i < len && c3 == -1);
                if (c3 == -1)
                    break;
                out += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2));
                /* c4 */
                do {
                    c4 = str.charCodeAt(i++) & 0xff;
                    if (c4 == 61)
                        return out;
                    c4 = base64DecodeChars[c4];
                }
                while (i < len && c4 == -1);
                if (c4 == -1)
                    break;
                out += String.fromCharCode(((c3 & 0x03) << 6) | c4);
            }
            return out;
        };

        /*
         * [ utf16 to utf8 ]
         * @str {string} utf16 string
         * @return {string} utf8 string
         */
        var utf16to8 = function(str) {
            var out, i, len, c;
            out = "";
            len = str.length;
            for (i = 0; i < len; i++) {
                c = str.charCodeAt(i);
                if ((c >= 0x0001) && (c <= 0x007F)) {
                    out += str.charAt(i);
                }
                else
                if (c > 0x07FF) {
                    out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
                    out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
                    out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
                }
                else {
                    out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
                    out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
                }
            }
            return out;
        };

        /*
         * [ utf8 to utf16 ]
         * @str {string} utf8 string
         * @return {string} utf16 string
         */
        var utf8to16 = function(str) {
            var out, i, len, c;
            var char2, char3;
            out = "";
            len = str.length;
            i = 0;
            while (i < len) {
                c = str.charCodeAt(i++);
                switch (c >> 4) {
                    case 0:
                    case 1:
                    case 2:
                    case 3:
                    case 4:
                    case 5:
                    case 6:
                    case 7:
                        // 0xxxxxxx 
                        out += str.charAt(i - 1);
                        break;
                    case 12:
                    case 13:
                        // 110x xxxx 10xx xxxx 
                        char2 = str.charCodeAt(i++);
                        out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
                        break;
                    case 14:
                        // 1110 xxxx10xx xxxx10xx xxxx 
                        char2 = str.charCodeAt(i++);
                        char3 = str.charCodeAt(i++);
                        out += String.fromCharCode(((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0));
                        break;
                }
            }
            return out;
        };

        /*
         * [ utf8 encode ]
         * @str {string} string
         * @return {string} string after utf8 encode
         */
        var encodeUTF8 = function(str) {
            var temp = "", rs = "";
            for (var i = 0, len = str.length; i < len; i++) {
                temp = str.charCodeAt(i).toString(16);
                rs += "\\u" + new Array(5 - temp.length).join("0") + temp;
            }
            return rs;
        };

        /*
         * [ utf8 decode ]
         * @str {string} string
         * @return {string} string after utf8 decode
         */
        var decodeUTF8 = function(str) {
            return str.replace(/(\\u)(\w{4}|\w{2})/gi, function($0, $1, $2) {
                return String.fromCharCode(parseInt($2, 16));
            });
        };

        /*
         * [ float addition ]
         * @arg1 {float} float1 
         * @arg2 {float} float2
         * @return {float} float1 + float2
         */
        var accAdd = function(arg1, arg2) {
            var c, d, e;
            try {
                c = arg1.toString().split(".")[1].length;
            } catch (f) {
                c = 0;
            }
            try {
                d = arg2.toString().split(".")[1].length;
            } catch (f) {
                d = 0;
            }
            return e = Math.pow(10, Math.max(c, d)), (mul(arg1, e) + mul(arg2, e)) / e;
        };

        /*
         * [ float subtraction ]
         * @arg1 {float} float1 
         * @arg2 {float} float2
         * @return {float} float1 - float2
         */
        var accSub = function(arg1, arg2) {
            var c, d, e;
            try {
                c = arg1.toString().split(".")[1].length;
            } catch (f) {
                c = 0;
            }
            try {
                d = arg2.toString().split(".")[1].length;
            } catch (f) {
                d = 0;
            }
            return e = Math.pow(10, Math.max(c, d)), (mul(arg1, e) - mul(arg2, e)) / e;
        };

        /*
         * [ float multiplication ]
         * @arg1 {float} float1 
         * @arg2 {float} float2
         * @return {float} float1 * float2
         */
        var accMul = function(arg1, arg2) {
            var c = 0,
                    d = arg1.toString(),
                    e = arg2.toString();
            try {
                c += d.split(".")[1].length;
            } catch (f) {
            }
            try {
                c += e.split(".")[1].length;
            } catch (f) {
            }
            return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c);
        };

        /*
         * [ float division ]
         * @arg1 {float} float1 
         * @arg2 {float} float2
         * @return {float} float1 / float2
         */
        var accDiv = function(arg1, arg2) {
            var c, d, e, f = 0;
            try {
                e = arg1.toString().split(".")[1].length;
            } catch (g) {
            }
            try {
                f = arg2.toString().split(".")[1].length;
            } catch (g) {
            }
            return c = Number(arg1.toString().replace(".", "")), d = Number(arg2.toString().replace(".", "")), mul(c / d, Math.pow(10, f - e));
        };

        /*
         * [ center horizontally ]
         * @x {integer} x-axis 
         * @return {integer} horizontally center value
         */
        var horCenter = function(x) {
            return (document.documentElement.clientWidth - x) / 2;
        };

        /*
         * [ vertical center ]
         * @y {integer} y-axis 
         * @return {integer} vertical center value
         */
        var verCenter = function(y) {
            return (document.documentElement.clientHeight - y) / 2 + document.documentElement.scrollTop;
        };

        /*
         * [ Relative path into absolute path ]
         * @pathName {string} relative path 
         * @return {string} absolute path
         */
        var convertFullPathName = function(pathName)
        {
            var fullPathName = pathName.replace(/(^\s*)|(\s*$)/g, "");
            var headStr = "";
            var footStr = "";
            if ('' == fullPathName) {
                return fullPathName;
            }

            if ('/' == fullPathName.indexOf[0]) {
                return fullPathName;
            }

            /*
             *   remove all "/./" in $PathName
             */
            while (1) {
                var findNum = fullPathName.lastIndexOf('/./');
                if (-1 != findNum) {
                    headStr = fullPathName.substring(0, findNum);
                    footStr = fullPathName.substr(findNum + 2);
                    fullPathName = headStr + footStr;
                } else {
                    break;
                }
            }

            /*
             *   remove all "//" in $PathName
             */
            while (1) {
                var findNum = fullPathName.lastIndexOf('//');
                if (-1 != findNum) {
                    headStr = fullPathName.substring(0, findNum);
                    footStr = fullPathName.substr(findNum + 1);
                    fullPathName = headStr + footStr;
                } else {
                    break;
                }
            }

            /*
             *   remove all "/../" in $PathName
             */
            while (1) {
                var findNum = fullPathName.indexOf('/../');
                if (-1 != findNum) {
                    if (0 == findNum) {
                        headStr = "";
                        footStr = fullPathName.substr(findNum + 3);
                        fullPathName = headStr + footStr;
                    } else {
                        headStr = fullPathName.substring(0, findNum);
                        headStr = fullPathName.substring(0, headStr.lastIndexOf("/"));
                        footStr = fullPathName.substr(findNum + 3);
                        fullPathName = headStr + footStr;
                    }
                } else {
                    break;
                }
            }

            /*
             *   remove "/.." at the end of $PathName
             */
            if ("/.." == fullPathName.substr(fullPathName.length - 3)) {
                headStr = fullPathName.substring(0, fullPathName.length - 3);
                fullPathName = fullPathName.substring(0, headStr.lastIndexOf("/"));
            }

            /*
             *   remove "/." at the end of $PathName
             */
            if ("/." == fullPathName.substr(fullPathName.length - 2)) {
                fullPathName = fullPathName.substring(0, fullPathName.length - 2);
            }

            /*
             *   remove "/" at the end of $PathName
             */
            if ("/" == fullPathName.substr(fullPathName.length - 1)) {
                fullPathName = fullPathName.substring(0, fullPathName.length - 1);
            }

            if ("" == fullPathName) {
                fullPathName = "/";
            }

            return fullPathName;

        };

        /*
         * [ string if start with ]
         * @str1 {string} primary value
         * @str2 {string} search value
         * @return {boolen} true | false
         */
        var startWith = function(str1, str2) {
            return str1.indexOf(str2) == 0;
        };

        /*
         * [ string if end with ]
         * @str1 {string} primary value
         * @str2 {string} search value
         * @return {boolen} true | false
         */
        var endWith = function(str1, str2) {
            var d = str1.length - str2.length;
            return (d >= 0 && str1.lastIndexOf(str2) == d);
        };

        //help
        /*
         * [ help document ]
         * @return {} Open the help documentation page
         */
        var help = function() {
            var url = "";
            window.open(url, '_brank', 'height=600,width=480,top=0,left=0,status=no,toolbar=no,menubar=no,location=no,scrollbars=yes');
            return true;
        };

        return {
            'version': version,
            'isEmpty': isEmpty,
            'isDate': isDate,
            'isTelephone': isTelephone,
            'isMobile': isMobile,
            'isEmail': isEmail,
            'isIDCard': isIDCard,
            'isNumber': isNumber,
            'isMoney': isMoney,
            'isDecimal': isDecimal,
            'isPost': isPost,
            'isURL': isURL,
            'isValidUserName': isValidUserName,
            'isValidReg': isValidReg,
            'isValidLength': isValidLength,
            'strReverse': strReverse,
            'strCut': strCut,
            'getHost': getHost,
            'getURL': getURL,
            'checkUrlState': checkUrlState,
            'htmlEncode': htmlEncode,
            'htmlDecode': htmlDecode,
            'setCookie': setCookie,
            'getCookie': getCookie,
            'addFavorite': addFavorite,
            'ip2int': ip2int,
            'int2ip': int2ip,
            'getPageHeight': getPageHeight,
            'getPageWidth': getPageWidth,
            'getViewSize': getViewSize,
            'getPageScrollLeft': getPageScrollLeft,
            'getPageScrollTop': getPageScrollTop,
            'back2Top': back2Top,
            'openWindow': openWindow,
            'ltrim': ltrim,
            'rtrim': rtrim,
            'trim': trim,
            'toDBC': toDBC,
            'toCDB': toCDB,
            'base64encode': base64encode,
            'base64decode': base64decode,
            'utf16to8': utf16to8,
            'utf8to16': utf8to16,
            'encodeUTF8': encodeUTF8,
            'decodeUTF8': decodeUTF8,
            'accAdd': accAdd,
            'accSub': accSub,
            'accMul': accMul,
            'accDiv': accDiv,
            'horCenter': horCenter,
            'verCenter': verCenter,
            'convertFullPathName': convertFullPathName,
            'startWith': startWith,
            'endWith': endWith,
            'help': help
        };
    })();

    return js_cmn;
});

你可能感兴趣的:(JavaScript)