How to extract base URL from a string in JavaScript?
Solution 1
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.
var pathArray = "https://somedomain.com".split( '/' );
var protocol = pathArray[0];
var host = pathArray[2];
var url = protocol + '//' + host;
Or use Davids solution from below.
Solution 2
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 URL http://www.sitename.com/article/2009/09/14/this-is-an-article/
is http://www.sitename.com
.
To target browsers without support for location.origin
use the following concise polyfill:
if (typeof location.origin === 'undefined')
location.origin = location.protocol + '//' + location.host;
Solution 3
Don't need to use jQuery, just use
location.hostname
Solution 4
There is no reason to do splits to get the path, hostname, etc from a string that is a link. You just need to use a link
//create a new element link with your link
var a = document.createElement("a");
a.href="http://www.sitename.com/article/2009/09/14/this-is-an-article/";
//hide it from view when it is added
a.style.display="none";
//add it
document.body.appendChild(a);
//read the links "features"
alert(a.protocol);
alert(a.hostname)
alert(a.pathname)
alert(a.port);
alert(a.hash);
//remove it
document.body.removeChild(a);
You can easily do it with jQuery appending the element and reading its attr.
Update: There is now new URL()
which simplifies it
const myUrl = new URL("https://www.example.com:3000/article/2009/09/14/this-is-an-article/#m123")
const parts = ['protocol', 'hostname', 'pathname', 'port', 'hash'];
parts.forEach(key => console.log(key, myUrl[key]))
Solution 5
Well, URL API object avoids splitting and constructing the url's manually.
let url = new URL('https://stackoverflow.com/questions/1420881');
alert(url.origin);
Related videos on Youtube
Comments
-
Bungle almost 3 years
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.
-
davidmpaz about 4 yearsThe now days answer should be this one below
-
-
Bungle over 14 yearsThanks for the reply, but again, I'm trying to extract the base URL from a string, rather than the actual document URL. I don't think this will help me - though please correct me if I'm wrong.
-
Admin over 14 yearspathArray = String("YourHost.com/url/nic/or/not").split( '/' ); host = pathArray[2];
-
Bungle over 14 yearsThanks - I can't use that with a string, though, can I? My understanding is that will only work with the document URL.
-
Admin over 14 yearssplit works for strings, does not matter where are they coming from
-
Bungle over 14 yearsHmm, from my limited regex skills, it looks like that's at least close. I'll add some more information to the question to see if I can help narrow down the best regex.
-
Bungle over 14 yearsAhhh, I see what happened. Rafal's example was indeed correct, but the "http://" prefix meant that it was interpreted as a link in his comment, so it was truncated from the visible text.
-
Admin over 14 yearsYep, It depends if You have http or not. You can always run one more test if first array elm is http or not :)
-
Tim Down over 14 yearshttps URLs? Host names not starting with www? Why capture the www anyway?
-
Tim Down over 14 yearsWhy add 50K of jQuery when you've shown how to do it without jQuery in a few bytes?
-
epascarello over 14 yearsBecause the poster says they are using jQuery.
-
Clement Herreman over 14 yearsI don't know, the OP asked how to catch a url, and in his example there was http & www.
-
Tim Down over 14 yearsAh yes, fair enough. Though when it's as simple as this I see no value in using the extra layer of abstraction that using jQuery would add.
-
ErikE over 13 yearsWhy all the variable declaration?
url = 'sitename.com/article/2009/09/14/this-is-an-article'; newurl = 'http://' + url.split('/')[0];
-
sroebuck over 12 years
window.location.hostname
will miss of the port number if given, so usewindow.location.host
. So the complete 'basename' including the trailing slash would be:window.location.protocol+"//"+window.location.host + "/";
-
trusktr over 12 yearsWe're assuming the whole site runs on jqUERY in that case, kquery would indeed simplify things.
-
BMiner over 12 yearsEwww... this is not the best way to do this... If extracting from window.location.href, use window.location. Otherwise, use a regex.
-
Darrell Brogdon about 12 yearsActually, window.location.hostname is still useful if, as in my case, you need to provide a different port number.
-
Katai about 11 yearsThis should be considered the correct answer - it keeps the protocol
-
Chalist almost 11 years
pathArray = window.location.href.split( '/' );
yes? -
Admin over 10 yearspathArray = window.location.href.split( '/' ); protocol = pathArray[0]; host = pathArray[2]; url = protocol + '://' + host;
//now url === "http:://stackoverflow.com"
checkout::
-
David over 10 yearsThis will not include protocol and port.
-
ewitkows about 10 yearsI agree with @TamilVendhan, the code above generates 2 colon's in the protocol section of the URL. Code should probably read
url = protocol + '//' + host;
-
ScorpionKing2k5 over 9 yearsI don't think it's required to append the anchor element to the DOM.
-
Dariux over 9 yearsI updated one line to get rid of query string: host = pathArray[2].split('?')[0];
-
mido about 9 yearsfails in the case where
location.pathname = '/'
-
Dehli over 8 yearsI think it should be
myAnchor.prop('hostname')
. I'm guessing that jQuery has changed in the last 5 years... Thanks for the answer! -
thomasf1 almost 8 yearsI think I´m missing something... Where is toUrl coming from?
-
Jan H over 7 yearsThe fist part of the solution in this answer does not consider credentials in the URL i.e. username:[email protected]/some-path. This can be resolved by adding if(host && host.indexOf("@") !== -1) host = host.split("@")[1];
-
dinvlad about 7 yearswhy not simply location.href.split('/', 3).join('/')?
-
harvzor about 7 yearsVery nice! This even works when creating a Firefox (53) WebExtension.
-
Florian Straub over 6 yearsAs mentioned above works without adding it to the DOM. Maybe you want to add the missing ; signs .. Pretty smart.Thanks!
-
Preet over 6 yearsPlease add brief description.
-
devansvd almost 6 yearshere is the one liner using URL API, no need to split and construct the url manually stackoverflow.com/a/50449208/6333644
-
RBT almost 5 yearsFrom review queue: May I request you to please add some context around your source-code. Code-only answers are difficult to understand. It will help the asker and future readers both if you can add more information in your post.
-
Oleg over 4 years
a.origin
is also usefull pretty often - it's equal toa.protocol + '//' + a.hostname
-
Jonno over 4 years@Oleg It seems to take port too, eg:
a.protocol + '//' + a.hostname + ':' + a.port
-
davidmpaz about 4 yearsPlease stop. The now days answer is the one provided by devensvd below