In joomla php there I can use $this->baseurl to get the base path, but I wanted to get the base path in jquery.
The base path may be any of the following example:
http://www.example.com/
http://localhost/example
http://www.example.com/sub/example
The example may also change.
I think this will work well for you:
var base_url = window.location.origin;
var host = window.location.host;
var pathArray = window.location.pathname.split( '/' );
This one will help you...
var getUrl = window.location;
var baseUrl = getUrl .protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];
This will get base url
var baseurl = window.location.origin+window.location.pathname;
document.baseURI returns base URL also respecting the value in <base/> tag
https://developer.mozilla.org/en-US/docs/Web/API/Node/baseURI
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 + "' />";
the easiest way to get base url in JavaScript
window.location.origin
This is not possible from javascript, because this is a server-side property. Javascript on the client cannot know where joomla is installed. The best option is to somehow include the value of $this->baseurl into the page javascript and then use this value (phpBaseUrl).
You can then build the url like this:
var loc = window.location;
var baseUrl = loc.protocol + "//" + loc.hostname + (loc.port? ":"+loc.port : "") + "/" + phpBaseUrl;
var getUrl = window.location;
var baseurl = getUrl.origin; //or
var baseurl = getUrl.origin + '/' +getUrl.pathname.split('/')[1];
But you can't say that the baseurl() of CodeIgniter(or php joomla) will return the same value, as it is possible to change the baseurl in the .htaccess file of these frameworks.
For example :
If you have an .htaccess file like this in your localhost :
RewriteEngine on
RewriteBase /CodeIgniter/
RewriteCond $1 !^(index.php|resources|robots.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
The $this->baseurl() will return http://localhost/CodeIgniter/
Had the same issue a while ago, my problem was, I simply needed the base url. There are a lot of detailed options here but to get around this, simply use the window.location object. Actually type this in the browser console and hit enter to select your options there. Well for my case it was simply:
window.location.origin
I've run into this need on several Joomla project. The simplest way I've found to address is to add a hidden input field to my template:
<input type="hidden" id="baseurl" name="baseurl" value="<?php echo $this->baseurl; ?>" />
When I need the value in JavaScript:
var baseurl = document.getElementById('baseurl').value;
Not as fancy as using pure JavaScript but simple and gets the job done.
You can easily get it with:
var currentUrl = window.location.href;
or, if you want the original URL, use:
var originalUrl = window.location.origin;
The format is hostname/pathname/search
So the url is :
var url = window.location.hostname + window.location.pathname + window.location.hash
For your case
window.location.hostname = "stackoverflow.com"
window.location.pathname ="/questions/25203124/how-to-get-base-url-with-jquery-or-javascript"
window.location.hash = ""
So basically the baseurl = hostname = window.location.hostname
I am surprised that non of the answers consider the base url if it was set in <base> tag. All current answers try to get the host name or server name or first part of address. This is the complete logic which also considers the <base> tag (which may refer to another domain or protocol):
function getBaseURL(){
var elem=document.getElementsByTagName("base")[0];
if (typeof(elem) != 'undefined' && elem != null){
return elem.href;
}
return window.location.origin;
}
Jquery format:
function getBaseURL(){
if ($("base").length){
return $("base").attr("href");
}
return window.location.origin;
}
Without getting involved with the logic above, the shorthand solution which considers both <base> tag and window.location.origin:
Js:
var a=document.createElement("a");
a.href=".";
var baseURL= a.href;
Jquery:
var baseURL= $('<a href=".">')[0].href
Final note: for a local file in your computer (not on a host) the window.location.origin only returns the file:// but the sorthand solution above returns the complete correct path.
Here's a short one:
const base = new URL('/', location.href).href;
console.log(base);
I would recommend for everyone to create HTML base tag in development, then assign the href dynamically, so in production whatever host a client uses, it will automacically addapt to it:
<html>
<title>Some page title</titile>
<script type="text/javascript">
var head = document.getElementsByTagName('head')[0];
var base = document.createElement("base");
base.href = window.document.location.origin;
head.appendChild(base);
</script>
</head>
...
So if you are in localhot:8080, you will reach every linked or referenced file from the base, eg: http://localhost:8080/some/path/file.html
If you are in www.example.com, it will be http://www.example.com/some/path/file.html
Also note that, every location you're on, you should not use references like globs in hrefs, eg: Parent location causes http://localhost:8080/ not http://localhost:8080/some/path/.
Pretent you reference all hyperlinks as full sentenced without the bas url.
window.location.origin+"/"+window.location.pathname.split('/')[1]+"/"+page+"/"+page+"_list.jsp"
almost same as Jenish answer but a little shorter.
I was just on the same stage and this solution works for me
In the view
<?php
$document = JFactory::getDocument();
$document->addScriptDeclaration('var base = \''.JURI::base().'\'');
$document->addScript('components/com_name/js/filter.js');
?>
In js file you access base as a variable for example in your scenario:
console.log(base) // will print
// http://www.example.com/
// http://localhost/example
// http://www.example.com/sub/example
I do not remember where I take this information to give credit, if I find it I will edit the answer
A simpler answer is here, window.location.href = window.location.origin;
Easy
$('<img src=>')[0].src
Generates a img with empty src-name forces the browser to calculate the base-url by itself, no matter if you have /index.html or anything else.
var getUrl = window.location;
var baseUrl = getUrl .protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];
Here's something quick that also works with file:// URLs.
I came up with this one-liner:
[((1!=location.href.split(location.href.split("/").pop())[0].length?location.href.split(location.href.split("/").pop())[0]:(location.protocol,location.protocol+"//" + location.host+"/"))).replace(location.protocol+"//"+location.protocol+"//"+location.protocol+"://")]
You mentioned that the example.com may change so I suspect that actually you need the base url just to be able to use relative path notation for your scripts. In this particular case there is no need to use scripting - instead add the base tag to your header:
<head>
<base href="http://www.example.com/">
</head>
I usually generate the link via PHP.
In case anyone would like to see this broken out into a very robust function
function getBaseURL() {
var loc = window.location;
var baseURL = loc.protocol + "//" + loc.hostname;
if (typeof loc.port !== "undefined" && loc.port !== "") baseURL += ":" + loc.port;
// strip leading /
var pathname = loc.pathname;
if (pathname.length > 0 && pathname.substr(0,1) === "/") pathname = pathname.substr(1, pathname.length - 1);
var pathParts = pathname.split("/");
if (pathParts.length > 0) {
for (var i = 0; i < pathParts.length; i++) {
if (pathParts[i] !== "") baseURL += "/" + pathParts[i];
}
}
return baseURL;
}
Split and join the URL:
const s = 'http://free-proxy.cz/en/abc'
console.log(s.split('/').slice(0,3).join('/'))
Getting the base url
|Calls controller from js
function getURL() {
var windowurl = window.location.href;
var baseUrl = windowurl.split('://')[1].split('/')[0]; //split function
var xhr = new XMLHttpRequest();
var url='http://'+baseUrl+'/url from controller';
xhr.open("GET", url);
xhr.send(); //object use to send
xhr.onreadystatechange=function() {
if(xhr.readyState==4 && this.status==200){
//console.log(xhr.responseText); //the response of the request
document.getElementById("id from where you called the function").innerHTML = xhr.responseText;
}
}
}
Put this in your header, so it will be available whenever you need it.
var base_url = "<?php echo base_url();?>";
You will get http://localhost:81/your-path-file or http://localhost/your-path-file.
Related
I have constructed a url path that are pointing to different hostname www.mysite.com, so for example:
var myMainSite = 'www.mymainsite.com' + '/somepath';
so this is equivalent to www.mymainsite.com/path/path/needthispath/somepath.
How I'm doing it now is like the code below and this gives me a bunch of indexes of the url in the console.log.
var splitUrl = myMainSite.split('/');
console.log looks like:
0: http://
1: www.
2: mysite.com
3: path
4: path
5: needthispath
6: somepath
and I concat them like splitUrl[5]+'/'+splitUrl[6] and it doesn't look pretty at all.
So my question is how to split/remove url location http://www.mymainsite.com/ to get the url path needthispath/somepath in js? Is there a quicker and cleaner way of doing this?
First solution (URL object)
The URL object can be used for parsing, constructing, normalizing, encoding URLs, and so on.
var url = 'http://www.mymainsite.com/somepath/path2/path3/path4';
var pathname = new URL(url).pathname;
console.log(pathname);
The URL interface represents an object providing static methods used
for creating object URLs.
See the documentation for URL interface on Mozilla MDN
The Browser support is pretty good in 2017 (~ 90% but not IE11 nor below)
Second solution (a kind of a hack)
var urlHack = document.createElement('a');
urlHack.href = 'http://www.mymainsite.com/somepath/path2/path3/path4';
console.log(urlHack.pathname);
// you can even call this object with these properties:
// protocol, host, hostname, port, pathname, hash, search, origin
Why don't you use the split function and work from there.
The split function will break your URL out fully and from there you just need to look for the second last and last items.
Here is an example:
var initial_url = 'http://www.mymainsite.com/path/path/needthispath/somepath';
var url = initial_url .split( '/' );
var updated_url= document.location.hostname + '/' + url[ url.length - 2 ] + '/' + url[ url.length - 1 ];
You can use the URL API, though support is variable.
Alternatively, you could use URI.js.
Both allow you to get different parts of an URL, as well as build new URLs from parts.
function url($url) {
var url = $url.split( '//' );
if (url[0] === "http:" || url[0] === "https:") {
var protocol = url[0] + "//";
var host = url[1].split( '/' )[0];
url = protocol + host;
var path = $url.split(url)[1];
return {
protocol: protocol,
host: host,
path: path
};
}
}
var $url = url("http://www.mymainsite.com/path/path/needthispath/somepath");
console.log($url.protocol); // http://
console.log($url.host); // www.mymainsite.com
console.log($url.path); // /path/path/needthispath/somepath
I've been searching all over for an answer to this and all of the answers I've found haven't been in JavaScript.
I need a way, in javascript, to check if a string starts with http, https, or ftp. If it doesn't start with one of those I need to prepend the string with http://. indexOf won't work for me I don't think as I need either http, https or ftp. Also I don't want something like google.com/?q=http://google.com to trigger that as being valid as it doesn't start with an http whereas indexOf would trigger that as being true (if I'm not entirely mistaken).
The closest PHP regex I've found is this:
function addhttp($url) {
if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
$url = "http://" . $url;
}
return $url;
}
Source: How to add http if its not exists in the url
I just don't know how to convert that to javascript. Any help would be greatly appreciated.
export const getValidUrl = (url = "") => {
let newUrl = window.decodeURIComponent(url);
newUrl = newUrl.trim().replace(/\s/g, "");
if(/^(:\/\/)/.test(newUrl)){
return `http${newUrl}`;
}
if(!/^(f|ht)tps?:\/\//i.test(newUrl)){
return `http://${newUrl}`;
}
return newUrl;
};
Tests:
expect(getValidUrl('https://www.test.com')).toBe('https://www.test.com');
expect(getValidUrl('http://www.test.com')).toBe('http://www.test.com');
expect(getValidUrl(' http : / / www.test.com')).toBe('http://www.test.com');
expect(getValidUrl('ftp://www.test.com')).toBe('ftp://www.test.com');
expect(getValidUrl('www.test.com')).toBe('http://www.test.com');
expect(getValidUrl('://www.test.com')).toBe('http://www.test.com');
expect(getValidUrl('http%3A%2F%2Fwww.test.com')).toBe('http://www.test.com');
expect(getValidUrl('www . test.com')).toBe('http://www.test.com');
This should work:
var pattern = /^((http|https|ftp):\/\/)/;
if(!pattern.test(url)) {
url = "http://" + url;
}
jsFiddle
var url = "http://something.com"
if( url.indexOf("http") == 0 ) {
alert("yeah!");
} else {
alert("No no no!");
}
Non-Regex declarative way:
const hasValidUrlProtocol = (url = '') =>
['http://', 'https://', 'ftp://'].some(protocol => url.startsWith(protocol))
This should work:
var re = /^(http|https|ftp)/
Refining previous answers a bit more, I used new RegExp(...) to avoid messy escapes, and also added an optional s.
var pattern = new RegExp('^(https?|ftp)://');
if(!pattern.test(url)) {
url = "http://" + url;
}
var pattern = new RegExp('^(https?|ftp)://');
console.log(pattern.test('http://foo'));
console.log(pattern.test('https://foo'));
console.log(pattern.test('ftp://foo'));
console.log(pattern.test('bar'));
Best readability I'd say is to use .startsWith('theString').
The code below checks for both http://, https:// and ftp:// and sets okUrl to a boolean true if any of them comply, by using the || which means or.
When you know if the url contains none of those strings, then just just add http:// to the start of the string either with literals (${})
let url = 'google.com'
const urlOK = url.startsWith('http://') || url.startsWith('https://') || url.startsWith('ftp://')
if (!urlOk) url = `http://${url}`
// => 'http://google.com'
or with simple string concat, which can be done in various ways, for example:
url = 'http://' + url
Read more about it, and test it, here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
I am looking to write a piece of javascript that will append a parameter to the current URL and then refresh the page - how can I do this?
this should work (not tested!)
var url = window.location.href;
if (url.indexOf('?') > -1){
url += '¶m=1'
}else{
url += '?param=1'
}
window.location.href = url;
Shorter than the accepted answer, doing the same, but keeping it simple:
window.location.search += '¶m=42';
We don't have to alter the entire url, just the query string, known as the search attribute of location.
When you are assigning a value to the search attribute, the question mark is automatically inserted by the browser and the page is reloaded.
Most of the answers here suggest that one should append the parameter(s) to the URL, something like the following snippet or a similar variation:
location.href = location.href + "¶meter=" + value;
This will work quite well for the majority of the cases.
However
That's not the correct way to append a parameter to a URL in my opinion.
Because the suggested approach does not test if the parameter is already set in the URL, if not careful one may end up with a very long URL with the same parameter repeated multiple times. ie:
https://stackoverflow.com/?¶m=1¶m=1¶m=1¶m=1¶m=1¶m=1¶m=1¶m=1¶m=1
at this point is where problems begin. The suggested approach could and will create a very long URL after multiple page refreshes, thus making the URL invalid. Follow this link for more information about long URL What is the maximum length of a URL in different browsers?
This is my suggested approach:
function URL_add_parameter(url, param, value){
var hash = {};
var parser = document.createElement('a');
parser.href = url;
var parameters = parser.search.split(/\?|&/);
for(var i=0; i < parameters.length; i++) {
if(!parameters[i])
continue;
var ary = parameters[i].split('=');
hash[ary[0]] = ary[1];
}
hash[param] = value;
var list = [];
Object.keys(hash).forEach(function (key) {
list.push(key + '=' + hash[key]);
});
parser.search = '?' + list.join('&');
return parser.href;
}
With this function one just will have to do the following:
location.href = URL_add_parameter(location.href, 'param', 'value');
If you are developing for a modern browser, Instead of parsing the url parameters yourself- you can use the built in URL functions to do it for you like this:
const parser = new URL(url || window.location);
parser.searchParams.set(key, value);
window.location = parser.href;
location.href = location.href + "¶meter=" + value;
This line of JS code takes the link without params (ie before '?') and then append params to it.
window.location.href = (window.location.href.split('?')[0]) + "?p1=ABC&p2=XYZ";
The above line of code is appending two params p1 and p2 with respective values 'ABC' and 'XYZ' (for better understanding).
function gotoItem( item ){
var url = window.location.href;
var separator = (url.indexOf('?') > -1) ? "&" : "?";
var qs = "item=" + encodeURIComponent(item);
window.location.href = url + separator + qs;
}
More compat version
function gotoItem( item ){
var url = window.location.href;
url += (url.indexOf('?') > -1)?"&":"?" + "item=" + encodeURIComponent(item);
window.location.href = url;
}
Please check the below code :
/*Get current URL*/
var _url = location.href;
/*Check if the url already contains ?, if yes append the parameter, else add the parameter*/
_url = ( _url.indexOf('?') !== -1 ) ? _url+'¶m='+value : _url+'?param='+value;
/*reload the page */
window.location.href = _url;
One small bug fix for #yeyo's thoughtful answer above.
Change:
var parameters = parser.search.split(/\?|&/);
To:
var parameters = parser.search.split(/\?|&/);
Try this
var url = ApiUrl(`/customers`);
if(data){
url += '?search='+data;
}
else
{
url += `?page=${page}&per_page=${perpage}`;
}
console.log(url);
Also:
window.location.href += (window.location.href.indexOf('?') > -1 ? '&' : '?') + 'param=1'
Just one liner of Shlomi answer usable in bookmarklets
I am trying to use the youtube data api to generate a video playlist.
However, the video urls require a format of:
youtube.com/watch?v=3sZOD3xKL0Y
but what the api generates is:
youtube.com/watch?v=3sZOD3xKL0Y&feature=youtube_gdata
So what I need to do is be able to select everything after and including the ampersand(&) and remove it from the url.
Any way to do this with javascript and some sort of regular expression?
What am I missing?
Why not:
url.split('?')[0]
Hmm... Looking for better way... here it is
var onlyUrl = window.location.href.replace(window.location.search,'');
Example: http://jsfiddle.net/SjrqF/
var url = 'youtube.com/watch?v=3sZOD3xKL0Y&feature=youtube_gdata';
url = url.slice( 0, url.indexOf('&') );
or:
Example: http://jsfiddle.net/SjrqF/1/
var url = 'youtube.com/watch?v=3sZOD3xKL0Y&feature=youtube_gdata';
url = url.split( '&' )[0];
Use this function:
var getCleanUrl = function(url) {
return url.replace(/#.*$/, '').replace(/\?.*$/, '');
};
// get rid of hash and params
console.log(getCleanUrl('https://sidanmor.com/?firstname=idan&lastname=mor'));
If you want all the href parts, use this:
var url = document.createElement('a');
url.href = 'https://developer.mozilla.org/en-US/search?q=URL#search-results-close-container';
console.log(url.href); // https://developer.mozilla.org/en-US/search?q=URL#search-results-close-container
console.log(url.protocol); // https:
console.log(url.host); // developer.mozilla.org
console.log(url.hostname); // developer.mozilla.org
console.log(url.port); // (blank - https assumes port 443)
console.log(url.pathname); // /en-US/search
console.log(url.search); // ?q=URL
console.log(url.hash); // #search-results-close-container
console.log(url.origin); // https://developer.mozilla.org
//user113716 code is working but i altered as below. it will work if your URL contain "?" mark or not
//replace URL in browser
if(window.location.href.indexOf("?") > -1) {
var newUrl = refineUrl();
window.history.pushState("object or string", "Title", "/"+newUrl );
}
function refineUrl()
{
//get full url
var url = window.location.href;
//get url after/
var value = url = url.slice( 0, url.indexOf('?') );
//get the part after before ?
value = value.replace('#System.Web.Configuration.WebConfigurationManager.AppSettings["BaseURL"]','');
return value;
}
This worked for me:
window.location.replace(window.location.pathname)
No splits.. :) The correct/foolproof way is to let the native browser BUILT-IN functions do the heavy lifting using urlParams, the heavy lifting is done for you.
//summary answer - this one line will correctly replace in all current browsers
window.history.replaceState({}, '', `${location.pathname}?${params}`);
// 1 Get your URL
let url = new URL('https://tykt.org?unicorn=1&printer=2&scanner=3');
console.log("URL: "+ url.toString());
// 2 get your params
let params = new URLSearchParams(url.search);
console.log("querys: " + params.toString());
// 3 Delete the printer param, Query string is now gone
params.delete('printer');
console.log("Printer Removed: " + params.toString());
// BELOW = Add it back to the URL, DONE!
___________
NOW Putting it all together in your live browser
// Above is a breakdown of how to get your params
// 4 then you simply replace those in your current browser!!
window.history.replaceState({}, '', `${location.pathname}?${params}`);
Sample working Javascript Fiddle here
You could use a RegEx to match the value of v and build the URL yourself since you know the URL is youtube.com/watch?v=...
http://jsfiddle.net/akURz/
var url = 'http://youtube.com/watch?v=3sZOD3xKL0Y';
alert(url.match(/v\=([a-z0-9]+)/i));
Well, I am using this:
stripUrl(urlToStrip){
let stripped = urlToStrip.split('?')[0];
stripped = stripped.split('&')[0];
stripped = stripped.split('#')[0];
return stripped;
}
or:
stripUrl(urlToStrip){
return urlToStrip.split('?')[0].split('&')[0].split('#')[0];
}
For example we have:
example.com/list/search?q=Somethink
And you need use variable url like this by window.location.href:
example.com/list/edit
From url:
example.com/list/search?q=Somethink
example.com/list/
var url = (window.location.href);
url = url.split('/search')[0];
url = (url + '/edit');
This is simple solution:-)
Is there a really easy way to start from a full URL:
document.location.href = "http://aaa.bbb.ccc.com/asdf/asdf/sadf.aspx?blah"
And extract just the host part:
aaa.bbb.ccc.com
There's gotta be a JavaScript function that does this reliably, but I can't find it.
Suppose that you have a page with this address: http://sub.domain.com/virtualPath/page.htm.
Use the following in page code to achieve those results:
Property
Result
window.location.host
sub.domain.com:8080 or sub.domain.com:80
window.location.hostname
sub.domain.com
window.location.protocol
http:
window.location.port
8080 or 80
window.location.pathname
/virtualPath
window.location.origin
http://sub.domain.com (Might include :port too*****)
Update: about the .origin
***** As the ref states, browser compatibility for window.location.origin is not clear. I've checked it in chrome and it returned http://sub.domain.com:port if the port is anything but 80, and http://sub.domain.com if the port is 80.
Special thanks to #torazaburo for mentioning that to me.
You could concatenate the location protocol and the host:
var root = location.protocol + '//' + location.host;
For a url, let say 'http://stackoverflow.com/questions', it will return 'http://stackoverflow.com'
The accepted answer didn't work for me since wanted to be able to work with any arbitary url's, not just the current page URL.
Take a look at the URL object:
var url = new URL("http://aaa.bbb.ccc.com/asdf/asdf/sadf.aspx?blah");
url.protocol; // "http:"
url.hostname; // "aaa.bbb.ccc.com"
url.pathname; // "/asdf/asdf/sadf.aspx"
url.search; // "?blah"
Use document.location object and its host or hostname properties.
alert(document.location.hostname); // alerts "stackoverflow.com"
There are two ways. The first is a variant of another answer here, but this one accounts for non-default ports:
function getRootUrl() {
var defaultPorts = {"http:":80,"https:":443};
return window.location.protocol + "//" + window.location.hostname
+ (((window.location.port)
&& (window.location.port != defaultPorts[window.location.protocol]))
? (":"+window.location.port) : "");
}
But I prefer this simpler method (which works with any URI string):
function getRootUrl(url) {
return url.toString().replace(/^(.*\/\/[^\/?#]*).*$/,"$1");
}
Let's suppose you have this url path:
http://localhost:4200/landing?query=1#2
So, you can serve yourself by the location values, as follow:
window.location.hash: "#2"
window.location.host: "localhost:4200"
window.location.hostname: "localhost"
window.location.href: "http://localhost:4200/landing?query=1#2"
window.location.origin: "http://localhost:4200"
window.location.pathname: "/landing"
window.location.port: "4200"
window.location.protocol: "http:"
window.location.search: "?query=1"
Now we can conclude you're looking for:
window.location.hostname
Try
document.location.host
or
document.location.hostname
use
window.location.origin
and for: "http://aaa.bbb.ccc.ddd.com/sadf.aspx?blah"
you will get: http://aaa.bbb.ccc.ddd.com/
There is another hack I use and never saw in any StackOverflow response :
using "src" attribute of an image will yield the complete base path of your site.
For instance :
var dummy = new Image;
dummy.src = '$'; // using '' will fail on some browsers
var root = dummy.src.slice(0,-1); // remove trailing '$'
On an URL like http://domain.com/somesite/index.html,
root will be set to http://domain.com/somesite/.
This also works for localhost or any valid base URL.
Note that this will cause a failed HTTP request on the $ dummy image.
You can use an existing image instead to avoid this, with only slight code changes.
Another variant uses a dummy link, with no side effect on HTTP requests :
var dummy = document.createElement ('a');
dummy.href = '';
var root = dummy.href;
I did not test it on every browser, though.
Check this:
alert(window.location.hostname);
this will return host name as www.domain.com
and:
window.location.host
will return domain name with port like www.example.com:80
For complete reference check Mozilla developer site.
I know this is a bit late, but I made a clean little function with a little ES6 syntax
function getHost(href){
return Object.assign(document.createElement('a'), { href }).host;
}
It could also be writen in ES5 like
function getHost(href){
return Object.assign(document.createElement('a'), { href: href }).host;
}
Of course IE doesn't support Object.assign, but in my line of work, that doesn't matter.
I would like to specify something. If someone want to get the whole url with path like I need, can use:
var fullUrl = window.location.protocol + "//" + window.location.hostname + window.location.pathname;
Regex provides much more flexibility.
//document.location.href = "http://aaa.bbb.ccc.com/asdf/asdf/sadf.aspx?blah
//1.
var r = new RegExp(/http:\/\/[^/]+/);
var match = r.exec(document.location.href) //gives http://aaa.bbb.ccc.com
//2.
var r = new RegExp(/http:\/\/[^/]+\/[^/]+/);
var match = r.exec(document.location.href) //gives http://aaa.bbb.ccc.com/asdf
My solution works in all web browsers including Microsoft Internet Explorer and doesn't use any regular expression, it's inspired of Noah Cardoza and Martin Konecny solutions:
function getHostname(href) {
if (typeof URL === 'object') {
// workaround for MS IE 11 (Noah Cardoza's solution but without using Object.assign())
var dummyNode = document.createElement('a');
dummyNode.href = href;
return dummyNode.hostname;
} else {
// Martin Konecny's solution
return new URL(href).hostname;
}
}
You can split the URL string using /
const exampleURL = "Https://exampleurl.com/page1/etc/etc"
const URLsplit = exampleURL.split("/")
console.log(URLsplit)
console.log(URLsplit[2])
Result. exampleurl.com