This is an extremely old question, but here are the approaches I personally use ...
Get Standard/Base URL
As many have already stated, this works for most situations.
var url = window.location.origin;
Get Absolute Base URL
However, this simple approach can be used to strip off any port numbers.
var url = "http://" + location.host.split(":")[0];
Edit: To address the concern, posed by Jason Rice, the following can be used to automatically insert the correct protocol type ...
var url = window.location.protocol + "//" + location.host.split(":")[0];
Set Base URL
As a bonus -- the base URL can then be redefined globally.
document.head.innerHTML = document.head.innerHTML + "<base href='" + url + "' />";