简体   繁体   中英

How to fetch a site name from URL in Javascript?

Is there an easy way to fetch a site name from a URL string?

Example:

http://www.mysite.com/mypath/mypage -> www.mysite.com
http://mysite.com/mypath/mypage     -> mysite.com

The JS code is executed on mongodb CLI side, not in a browser.

Try this:

url.href = "http://www.mysite.com/mypath/mypag";

url.protocol; // => "http:"
url.hostname; // => "example.com" // site name, you want

The window.document.location.href has the url of the page, and the window.document.location.hostname will have the sitename.

So,

console.log(window.document.location.hostname); // will log the sitename in the console

Easy.

window.location.hostname; //Domain name

$("title").text(); //Page name

and this too

var loc = window.location;

var filename = loc.pathname.split("/");
filename = filename[pathname.length-1];

alert("Domain: "+loc.hostname);
alert("Filename: "+filename);

You can abuse an anchor in order to get your desired data out of an URL. :D

function getDomain(url) {
  var anchor = document.createElement('a');
  anchor.setAttribute('href', url);

  return anchor.hostname;
}

console.log(getDomain('http://www.mysite.com/mypath/mypage'));
console.log(getDomain('http://mysite.com/mypath/mypage'));

http://jsfiddle.net/Js76M/

This one worked well for me:

urlString.split('/')[2]

I also need to get domain from a url to show only domain name on a reference section of my app.

I found this here: https://developer.mozilla.org/en-US/docs/Web/API/URL/URL

The URL() constructor returns a newly created URL object representing the URL defined by the parameters.

If the given base URL or the resulting URL are not valid URLs, the JavaScript TypeError exception is thrown.

function getDomain(url) {
   return new window.URL(url).hostname;
}

new URl(url) returns an object with the follows properties

hash: ""
host: "developer.mozilla.org"
hostname: "developer.mozilla.org"
href: "https://developer.mozilla.org/en-US/docs/Web/API/URL/URL"
origin: "https://developer.mozilla.org"
password: ""
pathname: "/en-US/docs/Web/API/URL/URL"
port: ""
protocol: "https:"
search: ""

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM