How to get Domain name from URL using jquery..?
In a browser
You can leverage the browser's URL parser using an <a>
element:
var hostname = $('<a>').prop('href', url).prop('hostname');
or without jQuery:
var a = document.createElement('a');a.href = url;var hostname = a.hostname;
(This trick is particularly useful for resolving paths relative to the current page.)
Outside of a browser (and probably more efficiently):
Use the following function:
function get_hostname(url) { var m = url.match(/^http:\/\/[^/]+/); return m ? m[0] : null;}
Use it like this:
get_hostname("http://example.com/path");
This will return http://example.com/
as in your example output.
Hostname of the current page
If you are only trying the get the hostname of the current page, use document.location.hostname
.
This worked for me.
http://tech-blog.maddyzone.com/javascript/get-current-url-javascript-jquery
$(location).attr('host'); www.test.com:8082$(location).attr('hostname'); www.test.com$(location).attr('port'); 8082$(location).attr('protocol'); http:$(location).attr('pathname'); index.php$(location).attr('href'); http://www.test.com:8082/index.php#tab2$(location).attr('hash'); #tab2$(location).attr('search'); ?foo=123
Try like this.
var hostname = window.location.originIf the URL is "http://example.com/path" then you will get "http://example.com" as the result.
This won't work for local domains
When you have URL like "https://localhost/MyProposal/MyDir/MyTestPage.aspx" and your virtual directory path is "https://localhost/MyProposal/" In such cases, you will get "https://localhost".