JavaScript常用方法

判断运行客户端

    function isPhone() {
        var flag = false;
        var userAgentInfo = navigator.userAgent;
        var Agents = ["Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod"];
        for (var i = 0; i < Agents.length; i++) {
            if (userAgentInfo.indexOf(Agents[i]) > 0) {
                flag = true;
                break;
            }
        }
        return flag;
    }

计算带中文的字符串长度(中文2字符)

    function getRealLength(str) {
        str = String(str);
        var len = str.match(/[\u4e80-\u9fff]/g).length;
        return str.length += len;
    }
    getRealLength('asd你好'); //7
    String.prototype.ChineseLength = function () {
        return this.replace(/[^\x00-\xff]/g, "**").length;
    };
    'asd你好'.ChineseLength(); //7

时间格式化

    function myFormatTime(fmt, date) {
        var o = {
            "M+": date.getMonth() + 1,  //月份
            "d+": date.getDate(),   //日
            "h+": date.getHours(),  //小时
            "m+": date.getMinutes(),    //分
            "s+": date.getSeconds(),    //秒
            "q+": Math.floor((date.getMonth() + 3) / 3),    //季度
            "S": date.getMilliseconds() //毫秒
        };
        if (/(y+)/.test(fmt))
            fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt))
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    }
    myFormatTime("yyyy年MM月dd日 hh:mm:ss:S 第q季度", new Date()); 
    // "2018年03月12日 11:22:42:263 第1季度"

文件大小格式化

    function bytesToSize(bytes) {
        if (bytes == 0) return '0 B';
        var k = 1024, sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
            i = Math.floor(Math.log(bytes) / Math.log(k));
        return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
    }
    bytesToSize(124213412); // "118 MB"

cookie获取

    function getcookie(objname) {
        var arrstr = document.cookie.split("; ");
        for (var i = 0; i < arrstr.length; i++) {
            var temp = arrstr[i].split("=");
            if (temp[0] == objname) return unescape(temp[1]);
        }
    }
    getcookie('cookieName'); //'cookieVal'

获取文件后缀名

    function GetExtensionFileName(pathfilename){
        var reg = /(\\+)/g;
        var pfn = pathfilename.replace(reg, "#");
        var arrpfn = pfn.split("#");
        var fn = arrpfn[arrpfn.length - 1];
        var arrfn = fn.split(".");
        return arrfn[arrfn.length - 1];
    }
    GetExtensionFileName('File.zip'); // zip

未完待更新

posted @ 2018-03-12 11:44  小桃酥的曲奇饼  阅读(90)  评论(0编辑  收藏  举报