如何从Javascript中的URL获取站点名称?

时间:2013-01-06 16:06:27

标签: javascript node.js mongodb serverside-javascript

是否有一种从URL字符串中获取网站名称的简单方法?

示例:

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

JS代码在mongodb CLI端执行,在浏览器中执行。

5 个答案:

答案 0 :(得分:3)

试试这个:

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

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

window.document.location.href有网页的网址,而window.document.location.hostname会有网站名称。

所以,

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

答案 1 :(得分:1)

易。

window.location.hostname; //Domain name

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

这也是

var loc = window.location;

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

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

答案 2 :(得分:0)

您可以滥用锚点,以便从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/

答案 3 :(得分:0)

这个对我很有用:

urlString.split( '/')[2]

答案 4 :(得分:-1)

我还需要从网址中获取域,以仅在应用程序的参考部分显示域名。

我在这里找到了: https://developer.mozilla.org/en-US/docs/Web/API/URL/URL

URL()构造函数返回一个新创建的URL对象,该对象表示 参数定义的网址。

如果给定的基本URL或生成的URL无效,则 JavaScript TypeError异常被抛出。

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

新的URl(url)返回具有以下属性的对象

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: ""