文本处理

1
2
3
4
5
// "\n" => "<br />"
function return2BR(text)
{
return (text || '').replace(/\n/g, "<br />");
}

常用计算

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
// 去除 URL 中的协议字段
function urlForRelativeScheme(url)
{
if(url === undefined) return undefined;
return url.replace(/^.*?:\/\//, '//');
}

// 根据生日计算年龄
function getAge(dateStr)
{
var today = new Date();
var birthday = new Date(dateStr);
var age = today.getFullYear() - birthday.getFullYear();
var m = today.getMonth() - birthday.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthday.getDate()))
{
--age;
}
return age;
}

// 获取 query 参数字典
function getQueryParams()
{
var arr = decodeURI(window.location.search.substr(1)).split("&");
var params = {};
for (var i = 0; i < arr.length; ++i)
{
var tmp_arr = arr[i].split("=");
params[tmp_arr[0]] = tmp_arr[1];
}
return params;
}

// 根据字典生成 query 字符串
function createQueryString(params)
{
var arr = [];
for(var key in params)
{
if(key && params.hasOwnProperty(key))
{
arr.push(key + '=' + params[key]);
}
}
return arr.join('&');
}

// 追加参数到 query 并重定向
function switchLocation(targetParams)
{
var params = getQueryParams();
params = $.extend(params, targetParams);
var search = createQueryString(params);
var l = window.location;
window.location.href = l.protocol + "//" + l.hostname + (l.port ? ':' + l.port: '') + l.pathname + '?' + search;
}