Skip to content

Instantly share code, notes, and snippets.

@Ausjorg
Created November 25, 2019 19:34
Show Gist options
  • Save Ausjorg/3514efa71782fc6a1820155519b3f69f to your computer and use it in GitHub Desktop.
Save Ausjorg/3514efa71782fc6a1820155519b3f69f to your computer and use it in GitHub Desktop.
returns obj with URL information
function parsePort(url) {
try { return parseInt(url.split(':')[2].split('/')[0]) }
catch { return null }
}
function parsePath(url) {
let tmp = null;
if (url.split('/')[3] == undefined) return '/';
(url.includes('?')) ? tmp = `/${url.split('/')[3].split('?')[0]}` : tmp = `/${url.split('/')[3]}`;
return tmp
}
function parseQuery(url) {
let tmp = [], obj = {};
(url.includes('?')) ? tmp = url.split('?')[1].split('&') : tmp = [];
for (var i of tmp) obj[i.split('=')[0]] = i.split('=')[1];
if (Object.keys(obj).length == 0) return null
return obj
}
function parseURL(url) {
let obj = {}
obj['url'] = url
obj['protocol'] = url.split(':')[0]
obj['host'] = url.split('//')[1].split('/')[0]
obj['hostname'] = obj['host'].split(':')[0]
obj['port'] = parsePort(url)
obj['path'] = parsePath(url)
obj['query'] = parseQuery(url)
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