I'm trying to find a relatively easy and reliable method to extract the base URL from a string variable using JavaScript (or jQuery).
For example, given something like:
http://www.sitename.com/article/2009/09/14/this-is-an-article/
I'd like to get:
http://www.sitename.com/
Is a regular expression the best bet? If so, what statement could I use to assign the base URL extracted from a given string to a new variable?
I've done some searching on this, but everything I find in the JavaScript world seems to revolve around gathering this information from the actual document URL using location.host or similar.
Don't need to use jQuery, just use
window.location.href gives the current url address from browser address bar
it can be any thing like https://stackoverflow.com/abc/xyz or https://www.google.com/search?q=abc tilllastbackslashregex.exec() run regex and retun the matched string till last backslash ie https://stackoverflow.com/abc/ or https://www.google.com/ respectively
This, works for me:
WebKit-based browsers, Firefox as of version 21 and current versions of Internet Explorer (IE 10 and 11) implement
location.origin
.location.origin
includes the protocol, the domain and optionally the port of the URL.For example,
location.origin
of the URLhttp://www.sitename.com/article/2009/09/14/this-is-an-article/
ishttp://www.sitename.com
.To target browsers without support for
location.origin
use the following concise polyfill:Edit: Some complain that it doesn't take into account protocol. So I decided to upgrade the code, since it is marked as answer. For those who like one-line-code... well sorry this why we use code minimizers, code should be human readable and this way is better... in my opinion.
Or use Davids solution from below.