robinmitra
2/20/2014 - 2:13 PM

Useful JavaScript snippets

Useful JavaScript snippets

// Parse URL

var parser = document.createElement('a');
parser.href = 'http://example.com:3000/pathname/?search=test#hash';

parser.protocol; // => 'http:'
parser.hostname; // => 'example.com'
parser.port;     // => '3000'
parser.pathname; // => '/pathname/'
parser.search;   // => '?search=test'
parser.hash;     // => '#hash'
parser.host;     // => 'example.com:3000'
// Remove trailing slash from a URL

var url = 'http://www.example.com/';

url = url.replace(/\/$/,'');  // => 'http://www.example.com'