JS實(shí)用技巧手記(二)

2018-06-17 19:23 更新

本系列文章旨在記錄一些實(shí)用的javascript技巧,既可以作為一個(gè)知識(shí)的積累,又可以作為閑暇時(shí)打發(fā)時(shí)間寫寫代碼的記錄。同時(shí)也方便日后翻閱~

 1. 實(shí)現(xiàn)字符串長度截取并在結(jié)尾添加…

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
26
27
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) {
            // 每次截取一個(gè)字符
            temp = str.substr(i, 1);
            if (patrn.exec(temp) == null) {
                // 如果是英文、半角
                icount = icount + 1
            } else {
                // 如果是中文、全角
                icount = icount + 2
            }
            // 字符串連接
            strre += temp
        } else {
            break
        }
    }
    return strre + "..."
}
// demo:
cutstr("xuanfeng", 2)  //xu...
cutstr("軒楓閣", 3)    //軒楓...

2. 獲取主域名

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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:
getHost("http://www.xuanfengge.com/page/2")   //www.xuanfengge.com

 

3. 清除左右空格

1
2
3
4
5
6
7
8
9
10
11
12
13
String.prototype.trim=function(){  
  return this.replace(/(^\s*)|(\s*$)/g, "");  
}  
String.prototype.ltrim=function(){  
  return this.replace(/(^\s*)/g,"");  
}  
String.prototype.rtrim=function(){  
  return this.replace(/(\s*$)/g,"");  
}  
// demo:
" xuanfeng    ".trim()  //xuanfeng
"  xuanfengge".ltrim()  //xuanfengge
"chrislee    ".rtrim()  //chrislee

 

4. 替換全部

1
2
3
4
5
String.prototype.replaceAll = function(s1, s2) {
    return this.replace(new RegExp(s1, "gm"), s2)
}
// demo:
"哈哈哈".replaceAll('哈','呵')   //呵呵呵

 

5. 轉(zhuǎn)義html標(biāo)簽

1
2
3
4
5
function HtmlEncode(text) {
    return text.replace(/&/g, '&amp').replace(/\"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
}
// demo:
HtmlEncode("<html></html>");    //&lt;html&gt;&lt;/html&gt;

 

6. 還原h(huán)tml標(biāo)簽

1
2
3
4
5
function HtmlDecode(text) {
    return text.replace(/&amp;/g, '&').replace(/&quot;/g, '\"').replace(/&lt;/g, '<').replace(/&gt;/g, '>')
}
// demo:
HtmlDecode("&lt;html&gt;&lt;/html&gt;");    //<html></html>

 

7. 時(shí)間日期格式轉(zhuǎn)換

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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;
}
// demo:
var date = new Date();
date.Format("YYYY-M-D");    //2013-5-8
date.Format("YYYY-MM-DD");  //2013-11-08

 

8. 判斷是否為數(shù)字類型

1
2
3
4
5
6
7
8
9
10
11
function isDigit(value) {
    var patrn = /^[0-9]*$/;
    if (patrn.exec(value) == null || value == "") {
        return false
    } else {
        return true
    }
}
// demo:
isDigit("sdf");     //false
isDigit(12);        //true

 

9. 設(shè)置cookie值

1
2
3
4
5
6
7
8
9
function setCookie(name, 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 = name + "=" + escape(value) + ";path=/;expires=" + exp.toGMTString() + ";domain=xuanfengge.com;"
}

 

10.獲取cookie值

1
2
3
4
5
function getCookie(name) {
    var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
    if (arr != null) return unescape(arr[2]);
    return null
}

 

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)