【问题标题】:Javascript for extracting only the domain and top level domain from a URL String用于仅从 URL 字符串中提取域和顶级域的 Javascript
【发布时间】:2018-01-15 20:07:15
【问题描述】:

我正在尝试创建一个 javascript 函数,该函数只能从 url 字符串中提取“域”和“顶级域”。

StackOverFlow 上的当前问题也不能解决非 URL 的答案。

例子:

  1. https://www.google.com/imgres?imgurl -> google.com
  2. yahoo.com/mail -> yahoo.com
  3. http://helloworld.net/index/test/help -> helloworld.net
  4. www.stackoverflow.com/ -> stackoverflow.com
  5. invalid.url -> "返回 false 或空字符串"

欢迎和感谢任何/所有帮助。谢谢。

【问题讨论】:

标签: javascript


【解决方案1】:

这很简单。

window.location.href 变量存储了网站当前的url。

有了这个变量,就可以得到top domain了。

var url = window.location.href
var split1 = url.split('//')[1];   // Get the string except the protocol.
var split2 = split1.split('/')[0];    // Get the domain url.
// Get top domain url.
var domain = split2;
if (split2.substring(0, 4) == 'www.')
    domain = split2.slice(4)

变量domain是你想要的值。

【讨论】:

  • https://accounts.google.com 甚至 https://foo.bar.foo.bar 都会失败。
  • 在这种情况下,顶级域将是“accounts.google.com”。我认为。它会像那样工作。
  • 对不起,我拼错了代码。获取 split2 变量时,必须使用变量 split1 但我使用了 url(我的错误。)
【解决方案2】:

正则表达式可以满足您的需求,例如:

^(?:https?://)?(?:[^/]+\.)?([^./]+\.[^./]+).*$

See on Debuggex

在 JS 中:

function extractDomain(url) {
  return url.replace(/^(?:https?:\/\/)?(?:[^\/]+\.)?([^.\/]+\.[^.\/]+).*$/, "$1");
}

如果您想处理包含点的 TLD(例如 .co.uk),那么恐怕唯一的解决方案就是对它们进行硬编码,例如:

^(?:https?://)?(?:[^/]+\.)?([^./]+\.(?:co\.uk|com|de|es|fr)).*$

See on Debuggex

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-06
    • 2021-08-19
    • 2015-08-03
    • 2010-11-07
    • 2018-01-04
    • 2017-12-30
    相关资源
    最近更新 更多