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.
I use a simple regex that extracts the host form the url:
and use it like this
Note, if the
url
does not end with a/
thehost
will not end in a/
.Here are some tests:
Well, URL API object avoids splitting and constructing the url's manually.