Created
November 25, 2019 19:47
-
-
Save Ausjorg/a9df52b753ddd146fbcbc588ef7c2bec to your computer and use it in GitHub Desktop.
Same as parseURL.js but with comments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function parsePort(url) { | |
// if able to grab item in port array position return it | |
try { return parseInt(url.split(':')[2].split('/')[0]) } | |
// else when fails return null | |
catch { return null } | |
} | |
function parsePath(url) { | |
let tmp = null; | |
// checks to see if on base path. if not returns home (base) path | |
if (url.split('/')[3] == undefined) return '/'; | |
// check for the query indicator (?). if it is there, remove query params, else return path | |
(url.includes('?')) ? tmp = `/${url.split('/')[3].split('?')[0]}` : tmp = `/${url.split('/')[3]}`; | |
return tmp | |
} | |
function parseQuery(url) { | |
let tmp = [], obj = {}; | |
// check if query indicator (?). If it is there return query params as array | |
(url.includes('?')) ? tmp = url.split('?')[1].split('&') : tmp = []; | |
// loop through query array and assign key/value based on query string | |
for (var i of tmp) obj[i.split('=')[0]] = i.split('=')[1]; | |
// check to see if obj is empty. if so return null (no query given) | |
if (Object.keys(obj).length == 0) return null | |
return obj | |
} | |
function parseURL(url) { | |
let obj = {} | |
obj['url'] = url // store orginal url | |
obj['protocol'] = url.split(':')[0] // splits into array and grabs first item | |
obj['host'] = url.split('//')[1].split('/')[0] // host includes name and port | |
obj['hostname'] = obj['host'].split(':')[0] // hostname only includes name | |
obj['port'] = parsePort(url) // see comments in parsePort() function | |
obj['path'] = parsePath(url) // see comments in parsePath() function | |
obj['query'] = parseQuery(url) // see comments in parseQuery() function | |
return obj | |
} | |
console.log(parseURL('http://localhost:3000/documents')) | |
console.log(parseURL('https://exampleapi.net/siteposts?publish=true&author=Austin Jorgensen')) | |
console.log(parseURL('https://google.com')) | |
console.log(parseURL('https://catfact.ninja/facts?limit=8')) | |
console.log(parseURL('http://localhost:3300')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment