Question

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.

Was it helpful?

Solution 4

This one worked well for me:

urlString.split('/')[2]

OTHER TIPS

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/

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: ""
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top