How to Parse a URL in JavaScript

John John (304)
2 minutes

Sure there are plugins that will do this for you, but here's a quick and easy way.

Posted in these interests:
h/javascript27 guides
h/webdev60 guides

Create an "a" tag and set the href to the URL you want to parse:

var parser = document.createElement("a");
parser.href = "";

Now use the parser object to get the URL parts:

parser.protocol; // =>"http:"
parser.hostname; // => ""
parser.port; // =>"8000"
parser.pathname; // => "/interests"; // => "?query=1"
parser.hash; // => "#bottom"; // => ""

This article expands on this idea to provide a little more functionality.

Make your object readable in console.
Zach Zach (249)
2 minutes

This short guide will show you how to pretty print a JSON object in the Chrome Developer Tools console.