美文网首页
JS使用技巧手记

JS使用技巧手记

作者: 请说Yes | 来源:发表于2017-03-06 17:03 被阅读0次

    1. 格式转换:3,456,123转为3456123

    function formatStr(str){
        return str.replace(/,/g,'');
    }
    //demo
    var str = '3,456,123'
    console.log(formatStr(str))
    

    2.格式转换:如3456123转为3,456,123

    function formatNum(num){
        var str_num = num + '';//转换成字符串
        var ret_num = '';
        var counter = 0;
        for(var i=str_num.length-1;i>=0;i--){
            ret_num = str_num.charAt(i) + ret_num;
            counter++;
            if(counter==3){
                counter = 0;
                if(i!=0){
                    ret_num = ',' + ret_num;
                }
            }
        }
        return ret_num;
    }
    // demo:
    var num = 3456123;
    console.log(formatNum(num));
    

    3. 随机数生成

            var rnd1 = Math.random();//返回0~1任意小数
            console.log(rnd1)
            var rnd2 = Math.floor(Math.random()*33);//返回0~33之间任意整数
            console.log(rnd2)
    

    4. 格式化显示数字

            var pi = 3.14159;
            console.log(pi.toFixed(2));//保留2位小数
            console.log(pi.toPrecision(9));//从左到右保留9位数字,不够补0
    

    5. 小数转整数

            var f = 1.5;
            console.log(Math.round(f));//四舍五入
            console.log(Math.ceil(f));//返回大于f的最小整数
            console.log(Math.floor(f));//返回小于f的最大整数
    

    6.实现字符串长度截取并在字符串后添加...

            function cutstr(str, len) {
                var temp;
                var icount = 0;
                var patrn = /[^\x00-\xff]/;  //表示汉字或者全角,即ASCII 编码不在0-255的字符
                var strre = "";
                for (var i = 0; i < str.length; i++) {
                    if (icount < len) {
                        // 每次截取一个字符
                        temp = str.substr(i, 1);
                        if (patrn.exec(temp) == null) {
                            // 如果是英文、半角
                            icount = icount + 1
                        } else {
                            // 如果是中文、全角
                            icount = icount + 2
                        }
                        // 字符串连接
                        strre += temp
                    } else {
                        break
                    }
                }
                return strre + "..."
            }
            // demo:
            console.log(cutstr("Tianzhihong", 4));
            console.log(cutstr("我是中国人", 5));
    

    7. 获取主域名

            function getHost(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;
            }
            // demo:
            console.log(getHost("https://www.baidu.com/s?ie=utf-8&f=3&rsv_bp=0&rsv_idx=1&tn=baidu&wd=%E4%B8%B4%E6%97%B6%20%E8%8B%B1%E6%96%87&rsv_pq=fe2c6b690033543f&rsv_t=e826BZYU7Lfmea068KJo57JWFCFA91Cos63Q9PCwIFlVuebah2RSbB0O94E&rqlang=cn&rsv_enter=1&rsv_sug3=8&rsv_sug1=7&rsv_sug7=100&rsv_sug2=0&prefixsug=%25E4%25B8%25B4%25E6%2597%25B6%2520&rsp=0&inputT=9138&rsv_sug4=10044"))
    

    8. 清除左右空格

            function trim(str){
                return str.replace(/(^\s*) | (\s*$)/g,"")
            }
            console.log(trim('tian   '));
    

    9. 时间日期格式转换

            Date.prototype.Format = function(formatStr) {
                var str = formatStr;
                var Week = ['日', '一', '二', '三', '四', '五', '六'];
                str = str.replace(/yyyy|YYYY/, this.getFullYear());
                str = str.replace(/yy|YY/, (this.getYear() % 100) > 9 ? (this.getYear() % 100).toString() : '0' + (this.getYear() % 100));
                str = str.replace(/MM/, (this.getMonth() + 1) > 9 ? (this.getMonth() + 1).toString() : '0' + (this.getMonth() + 1));
                str = str.replace(/M/g, (this.getMonth() + 1));
                str = str.replace(/w|W/g, Week[this.getDay()]);
                str = str.replace(/dd|DD/, this.getDate() > 9 ? this.getDate().toString() : '0' + this.getDate());
                str = str.replace(/d|D/g, this.getDate());
                str = str.replace(/hh|HH/, this.getHours() > 9 ? this.getHours().toString() : '0' + this.getHours());
                str = str.replace(/h|H/g, this.getHours());
                str = str.replace(/mm/, this.getMinutes() > 9 ? this.getMinutes().toString() : '0' + this.getMinutes());
                str = str.replace(/m/g, this.getMinutes());
                str = str.replace(/ss|SS/, this.getSeconds() > 9 ? this.getSeconds().toString() : '0' + this.getSeconds());
                str = str.replace(/s|S/g, this.getSeconds());
                return str;
            }
            function convertDate(str){
                var date = new Date(str);
                return date.Format('yyyyMMdd'); //这里写需要的转换格式
            }
            console.log(convertDate('2017-03-12'));
    

    10. 加载样式文件

            function loadStyle(url){
                try{
                    document.creatStyleSheet(url);
                }catch(e){
                    var linkcss = document.createElement('link');
                    linkcss.type = 'text/css';
                    linkcss.rel = 'stylesheet';
                    linkcss.href = url;
                    var head = document.getElementsByTagName('head')[0];
                    head.appendChild(linkcss);
                }
            }
            loadStyle('css/style.css');
    

    11. 十六进制颜色值的随机生成

    //js
            function randomColor(){
                var arrHex=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"],
                    strHex="#",
                    index;
                    for(var i=0;i<6;i++){
                        index=Math.floor(Math.random()*16);
                        strHex+=arrHex[index];
                    }
                return strHex;
            }
            document.getElementById('text').style.color = randomColor();
    //html
    <p id="text">我是中国人</p>
    

    相关文章

      网友评论

          本文标题:JS使用技巧手记

          本文链接:https://www.haomeiwen.com/subject/vrsugttx.html