| 1 |
import urlParse from 'url-parse'; |
| 2 |
/** |
| 3 |
* parseURL - decompose a URL into its parts |
| 4 |
* @param {String} url a URL |
| 5 |
* @return {Object} parts of the URL, including the following |
| 6 |
* |
| 7 |
* 'https://www.yahoo.com:1234/mypage?test=yes#abc' |
| 8 |
* |
| 9 |
* { |
| 10 |
* host: 'www.yahoo.com:1234', |
| 11 |
* protocol: 'https:', |
| 12 |
* search: '?test=yes', |
| 13 |
* hash: '#abc', |
| 14 |
* href: 'https://www.yahoo.com:1234/mypage?test=yes#abc', |
| 15 |
* pathname: '/mypage', |
| 16 |
* fullpath: '/mypage?test=yes' |
| 17 |
* } |
| 18 |
*/ |
| 19 |
export default function parseURL(url: string) { |
| 20 |
let parsedUrl = new urlParse(url); |
| 21 |
|
| 22 |
if (!parsedUrl.host) { |
| 23 |
// eslint-disable-next-line no-self-assign |
| 24 |
parsedUrl.href = parsedUrl.href; // IE: load the host and protocol |
| 25 |
} |
| 26 |
|
| 27 |
var pathname = parsedUrl.pathname; |
| 28 |
if (pathname.charAt(0) !== '/') { |
| 29 |
pathname = '/' + pathname; // IE: prepend leading slash |
| 30 |
} |
| 31 |
|
| 32 |
var host = parsedUrl.host; |
| 33 |
if (parsedUrl.port === '80' || parsedUrl.port === '443') { |
| 34 |
host = parsedUrl.hostname; // IE: remove default port |
| 35 |
} |
| 36 |
|
| 37 |
return { |
| 38 |
host: host, |
| 39 |
protocol: parsedUrl.protocol, |
| 40 |
search: parsedUrl.query, |
| 41 |
hash: parsedUrl.hash, |
| 42 |
href: parsedUrl.href, |
| 43 |
pathname: pathname, |
| 44 |
fullpath: pathname + (parsedUrl.query || '') + (parsedUrl.hash || '') |
| 45 |
}; |
| 46 |
} |