JS实用技巧手记(二)

2018-06-17 19:23 更新

本系列文章旨在记录一些实用的javascript技巧,既可以作为一个知识的积累,又可以作为闲暇时打发时间写写代码的记录。同时也方便日后翻阅~

 1. 实现字符串长度截取并在结尾添加…

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) {
            // 每次截取一个字符
            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. 转义html标签

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. 还原html标签

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. 时间日期格式转换

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. 判断是否为数字类型

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. 设置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
}

 

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号