1 |
|
2 |
|
3 |
|
4 | 'use strict';
|
5 |
|
6 | module.exports = class UrlHelper {
|
7 |
|
8 | static parse (url) {
|
9 | let index = url.indexOf('#'), anchor;
|
10 | if (index !== -1) {
|
11 | anchor = url.substring(index + 1);
|
12 | url = url.substring(0, index);
|
13 | }
|
14 | index = url.indexOf('?');
|
15 | let path = index !== -1 ? url.substring(0, index) : url;
|
16 | if (path.charAt(0) === '/') {
|
17 | path = path.substring(1);
|
18 | }
|
19 | if (path.charAt(path.length - 1) === '/') {
|
20 | path = path.substring(0, path.length - 1);
|
21 | }
|
22 | const segments = path.split('/');
|
23 | const params = {};
|
24 | if (index === -1) {
|
25 | return {segments, params, anchor};
|
26 | }
|
27 | url = url.substring(index + 1);
|
28 | for (const param of url.split('&')) {
|
29 | index = param.indexOf('=');
|
30 | if (index !== -1) {
|
31 | params[param.substring(0, index)] = param.substring(index + 1);
|
32 | }
|
33 | }
|
34 | return {segments, params, anchor};
|
35 | }
|
36 |
|
37 | static serialize (data) {
|
38 | if (!data) {
|
39 | return '';
|
40 | }
|
41 | const result = [];
|
42 | for (const key of Object.keys(data)) {
|
43 | if (data[key] !== undefined && data[key] !== null) {
|
44 | result.push(key +'='+ data[key]);
|
45 | }
|
46 | }
|
47 | return result.join('&');
|
48 | }
|
49 | }; |
\ | No newline at end of file |