forked from dhigginbotham/locationify
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
112 lines (93 loc) · 2.41 KB
/
index.js
File metadata and controls
112 lines (93 loc) · 2.41 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
var locationify = function(str) {
if (str) return locationify.parseHref(str);
return locationify;
};
// http schema/protocol
locationify.getProtocol = function (str) {
var re = /^\w?:/;
if (str) return str.match(re);
};
// strip off trailing slashes
locationify.stripTrailing = function (str) {
if (str[str.length - 1] == '/') str = str.substr(0, str.length - 1);
return str;
};
// get querystring params
locationify.parseParams = function (str) {
var params = {}, queries, temp, i, l;
var query = str;
var queryString = query.substring(query.indexOf('?') + 1);
queries = queryString.split("&");
for (i = 0, l = queries.length; i < l; i++) {
temp = queries[i].split('=');
params[temp[0]] = decodeURIComponent(temp[1]);
}
return params;
};
// accepts an array of paths and joins
// them back into a str
locationify.serializePaths = function (arr) {
if (arr && arr.length) return '/' + arr.join('/');
};
// serializes param obj, only works single
// level
locationify.serializeParams = function (obj) {
var param = null;
for (var k in obj) {
if (!param) param = [];
param.push(k + '=' + obj[k]);
}
return param.join('&');
};
locationify.parseHref = function (str) {
var pieces, protoHost, paramIndex, protocol, hashIndex, url;
// base url obj values
url = {
base: null,
host: null,
hash: null,
params: null,
pathname: null,
path: null,
protocol: null
};
if (!str) return url;
// reset/set current obj
url.base = str;
// match/strip protocol
protocol = locationify.getProtocol(str);
if (protocol) {
url.protocol = protocol[0];
str = str.replace(protocol[0], '');
}
// strip off #hash
hashIndex = str.indexOf('#');
if (hashIndex != -1) {
url.hash = str.split('#')[1];
str = str.substr(0, hashIndex);
}
// process params
paramIndex = str.indexOf('?');
if (paramIndex != -1) {
url.params = locationify.parseParams(str);
str = str.substr(0, paramIndex);
}
// strip any trailing slashes
str = locationify.stripTrailing(str);
// break pieces into array
protoHost = str.split('//');
if (protoHost[1]) {
pieces = protoHost[1].split('/');
url.protocol = protoHost[0];
} else {
pieces = str.split('/');
}
if (pieces.length) {
url.host = pieces[0];
if (pieces.length > 1) {
url.path = url.pathname = pieces.splice(1);
}
}
return url;
};
module.exports = locationify;