-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqurl.js
92 lines (71 loc) · 1.64 KB
/
qurl.js
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
91
92
var Qurl;
(function() {
'use strict';
var proto;
Qurl = function() {
if (!(this instanceof Qurl)) {
return new Qurl();
}
}
proto = Qurl.prototype;
proto.query = function(key, value) {
if (!key) {
return getSearch();
}
if (key && typeof(value) === 'undefined') {
return getSearch()[key];
}
if (key && typeof(value) !== 'undefined') {
return setSearch(key, value);
}
};
function getSearch() {
var string = window.location.search,
pairs = [],
obj = {};
if (!string) {
return obj;
}
string = string.replace('?', '');
pairs = string.split('&');
pairs.forEach(function(p) {
var pair = decodeURIComponent(p).split('='),
key = pair[0],
val = pair[1];
obj[key] = val;
});
return obj;
}
function setSearch(key, value) {
var search = getSearch(),
string = window.location.search;
if (value === false) {
delete search[key];
} else {
search[key] = value;
}
setSearchString(getSearchString(search));
return search;
}
function setSearchString(string) {
if (history.pushState) {
history.pushState({}, document.title, string);
}
}
function getSearchString(query) {
var pairs = [];
Object.keys(query).forEach(function(key) {
if (typeof query[key] === 'undefined') {
pairs.push(key);
} else {
pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(query[key] || ''));
}
});
if (pairs.length === 0) {
return '?';
} else {
return '?' + pairs.join('&');
}
}
Qurl.create = Qurl;
}());