【问题标题】:How do I return location.hostname without the trailing slash?如何返回不带斜杠的 location.hostname?
【发布时间】:2020-04-18 18:06:57
【问题描述】:

如果输入为https://example.com/page.html?query=string,我如何使用JavaScript返回字符串example.com

现在,如果我使用 window.location.hostname – 或 location.hostname – 返回值是
example.com/,但我想要example.com,没有尾部斜杠。


这个问题类似于@r1853 的“How to remove trailing slash from window.location.pathname”,但是因为 JavaScript 提供了许多方法来获取 URI 的一部分(location.hostnamelocation.hostlocation.href),并且因为格式正确的 URI是一个封闭的类,我认为有一个比使用正则表达式从它们中删除尾部斜杠更便宜的选择。

【问题讨论】:

标签: javascript string data-manipulation window.location trailing-slash


【解决方案1】:

只需将您的window.location.hostname 放入一个变量中:

let hostname = window.location.hostname;

然后使用substring 删除最后一个字符(即尾部斜杠)

hostname = hostname.substring(0, hostname.length - 1);

如果您想确保最后一个字符实际上是 /,那么您可以使用 if 语句:

if (hostname.charAt(hostname.length - 1) == '/') {
  hostname = hostname.substring(0, hostname.length - 1)
}

【讨论】:

  • 对于 URI 的那一部分,JavaScript 中是否没有其他机制,比如 window.location.hostnamebeforetheslash 或其他什么?
  • 我不知道
猜你喜欢
  • 2011-10-04
  • 1970-01-01
  • 2018-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多