I have domain name for eq.
1) http://www.abc.com/search 2) http://go.abc.com/work
I get only domain name from the above URL
Output like
1) http://www.abc.com/ 2) http://go.abc.com/
how can I do?
Firstly, we'd need to extract the host from the given URL value. We can use the URI class: String urlString = "https://www.baeldung.com/java-tutorial"; URI uri = new URI(urlString); String host = uri. getHost();
window.location.href returns the href (URL) of the current page. window.location.hostname returns the domain name of the web host. window.location.pathname returns the path and filename of the current page.
To access the domain name from an above URL, we can use the window. location object that contains a hostname property which is holding the domain name. Similarly, we can also use the document. domain property to access it.
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.)
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With