Clever Way of Extract URL Information in JS

Here’s a nice little way to extract URL information from a string. Rather than trying to parse/split the string into its parts (protocol, host, path, query) just use an a tag and access it’s properties to get the relative information you want.

1
2
3
4
5
6
7
8
9
var url    = 'https://www.google.co.uk/search?q=hello'
var anchor = document.createElement('a');

anchor.href = url;

var protocol = anchor.protocol; // 'https:'
var host     = anchor.hostname; // 'google.co.uk'
var path     = anchor.pathname; // '/search'
var query    = anchor.search;   // '?q=hello'

Simples.

js, url
Comments

Comments