-
Notifications
You must be signed in to change notification settings - Fork 0
/
QueryString.js
81 lines (65 loc) · 2.14 KB
/
QueryString.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
/**
* Add, remove, modify field in URL query string.
* https://github.com/hyeonseok/QueryString
*/
var QueryString = {
parseUrl: function (href) {
return {
'path': href.split('#')[0].split('?')[0],
'query': href.indexOf('?') > -1 ? href.split('?')[1].split('#')[0] : '',
'hash': href.split('#')[1] || ''
}
},
makeUrl: function (parsed) {
return parsed.path + (parsed.query.length > 0 ? '?' + parsed.query : '') + (parsed.hash.length > 0 ? '#' + parsed.hash : '');
},
getParameter: function (href, parameter) {
var parsed = this.parseUrl(href),
splited,
value = [],
i;
for (i = 0, splited = parsed.query.split('&'); i < splited.length; i++) {
if (splited[i].indexOf(parameter + '=') > -1 || splited[i].indexOf(encodeURIComponent(parameter) + '=') > -1) {
value.push(splited[i].split('=')[1]);
}
}
return value.length === 0 ? undefined : (value.length === 1 ? value[0] : value);
},
addParameter: function (href, parameter, value) {
var parsed = this.parseUrl(href),
query = [],
i;
if (parsed.query.indexOf(parameter + '=') > -1) {
for (i = 0, splited = parsed.query.split('&'); i < splited.length; i++) {
if (splited[i].indexOf(parameter + '=') === -1 && splited[i].indexOf(encodeURIComponent(parameter) + '=') === -1) {
query.push(splited[i]);
}
}
} else if (parsed.query.length > 0) {
query.push(parsed.query);
}
query.push(parameter + '=' + value);
parsed.query = query.join('&');
return this.makeUrl(parsed);
},
removeParameter: function (href, parameter) {
var parsed = this.parseUrl(href),
query = [],
i;
for (i = 0, splited = parsed.query.split('&'); i < splited.length; i++) {
if (splited[i].indexOf(parameter + '=') > -1 || splited[i].indexOf(encodeURIComponent(parameter) + '=') > -1) {
continue;
}
if (splited[i].length > 0) {
query.push(splited[i]);
}
}
parsed.query = query.join('&');
return this.makeUrl(parsed);
},
addQueryString: function (href, queryString) {
var parsed = this.parseUrl(href);
parsed.query += parsed.query.length > 0 && queryString.length > 0 ? '&' + queryString : '';
return this.makeUrl(parsed);
}
};