/ javascript

Parse URLs in browser without extra dependencies

Ow how to win without extra bundle bloat 😉

Parsing URLs in Node.js is easy - just use the built-in URL module.
On the front-end things get more interesting as it seems that, sigh, yet another dependency is needed. Turns out, it is quite easy to accomplish this on this end too. I also discovered this by pure accident 💙 although someone stumbling upon this post might be rolling their eyes. 😎

You can use element <a> to parse various attributes of a URL.

const a = document.createElement('a')
a.href = 'https://user:my-pass@vanja.gavric.org:5000/foo/bar/baz/?foo=bar&baz=qux#hash'

console.log(a.protocol) // 'https:'
console.log(a.username) // 'user'
console.log(a.password) // 'my-pass'
console.log(a.origin)   // 'https://vanja.gavric.org:5000'
console.log(a.hostname) // 'vanja.gavric.org'
console.log(a.port)     // '5000'
console.log(a.host)     // 'vanja.gavric.org:5000'
console.log(a.pathname) // '/foo/bar/baz/'
console.log(a.search)   // '?foo=bar&baz=qux'
console.log(a.hash)     // '#hash'

After reading more about this problem it turns out that there is a URL Web API, if the browser supports it (looking at you IE and Edge). And guess what? The syntax is the same as with Node:

const modernA = new URL('https://user:my-pass@vanja.gavric.org:5000/foo/bar/baz/?foo=bar&baz=qux#hash')

console.log(modernA)
// {
//   hash: '#hash',
//   host: 'vanja.gavric.org:5000',
//   hostname: 'vanja.gavric.org',
//   href: 'https://user:my-pass@vanja.gavric.org:5000/foo/bar/,baz/?foo=bar&baz=qux#hash'
//   origin: 'https://vanja.gavric.org:5000',
//   password: 'my-pass',
//   pathname: '/foo/bar/baz/',
//   port: '5000',
//   protocol: 'https:',
//   search: '?foo=bar&baz=qux',
//   searchParams: URLSearchParams,
//   username: 'user'
// }

In and out. Ciao!

Vanja

Vanja

Gadget junkie, shutterbug, runs on green tea, beer and chocolate.

Read More
Parse URLs in browser without extra dependencies
Share this