index.js
2.27 KB
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/**
* 页面公共逻辑和接口
* @author: xuqi<qi.xu@yoho.cn>
* @date: 2017/7/5
*/
/**
* 获取cookie值
* @param name [string] cookie键名
* @return [string] cookie值
*/
function cookie(name) {
var re = new RegExp(name + '=([^;$]*)', 'i'),
matchPattern = '$1';
return re.test(decodeURIComponent(document.cookie)) ? RegExp[matchPattern] : '';
}
/**
* 设置cookie
* @param name [string] cookie键名
* @param value [string] cookie值
* @pamra options [object] cookie参数项
*/
function setCookie(name, value, options) {
var expires = '',
path,
domain,
secure,
date;
if (typeof value !== 'undefined') {
options = options || {};
if (value === null) {
value = '';
options.expires = -1;
}
if (options.expires &&
(typeof options.expires === 'number' || options.expires.toUTCString)) {
if (typeof options.expires === 'number') {
date = new Date();
date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
} else {
date = options.expires;
}
expires = '; expires=' + date.toUTCString();
}
path = options.path ? '; path=' + options.path : '';
domain = options.domain ? '; domain=' + options.domain : '';
secure = options.secure ? '; secure' : '';
document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
}
}
/**
* query参数解析
* @return [object] query key-value map
*/
function queryString() {
var vars = {},
hash,
i,
search = window.location.search,
hashes = search ? decodeURIComponent(search).slice(1).split('&') : [];
for (i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars[hash[0]] = hash[1];
}
return vars;
}
/**
* 获取字符串长度(一个中文=2个字符)
* @param str [string]
* @return [num] 字符串长度
*/
function getStrLength(str) {
var cArr = str.match(/[\u4e00-\u9fa5a]/ig);
return str.length + (cArr === null ? 0 : cArr.length);
}
module.exports = {
cookie: cookie,
setCookie: setCookie,
queryString: queryString,
getStrLength: getStrLength
};