UNPKG

crocser

Version:

Fast, lightweight, tinny url parser

46 lines (44 loc) 1.78 kB
const parseUrl = (queryString) => { const info = queryString.split('/'); const protocol = info[0].substring(0, info[0].length - 1); const hostname = info[2]; const infoAboutDomain = hostname.split('.'); let subdomain = ''; let domain = ''; let domainWithoutSuffix = ''; let publicSuffix = ''; if (infoAboutDomain.length >= 3) { subdomain = infoAboutDomain[0]; for (let i = 1; i < infoAboutDomain.length - 1; i++) { if (domainWithoutSuffix.length === 0) { domainWithoutSuffix = infoAboutDomain[i]; } else { domainWithoutSuffix = domainWithoutSuffix + '.' + infoAboutDomain[i]; } } publicSuffix = infoAboutDomain[infoAboutDomain.length - 1]; domain = domainWithoutSuffix + '.' + publicSuffix; } if (infoAboutDomain.length === 2) { domainWithoutSuffix = infoAboutDomain[0]; publicSuffix = infoAboutDomain[1]; domain = domainWithoutSuffix + '.' + publicSuffix; } const paramMap = new Map(); if (info[info.length - 1].length !== 0) { let queryParamsRaw = info[info.length - 1].split('?')[1]; if (queryParamsRaw) { let queryParams = queryParamsRaw.split('&'); for (let i = 0; i < queryParams.length; i++) { let queryParamsArr = queryParams[i].split('='); for (let i = 0; i < queryParamsArr.length - 1; i++) { paramMap.set(queryParamsArr[i], queryParamsArr[i + 1]); } } } } const queryParamsResult = Array.from(paramMap); return { protocol, hostname, subdomain, domain, domainWithoutSuffix, publicSuffix, queryParamsResult }; }; export { parseUrl };