[英]How do I return location.hostname without the trailing slash?
How do I return the string example.com
using JavaScript if the input is https://example.com/page.html?query=string
?如果输入是
https://example.com/page.html?query=string
如何使用 JavaScript 返回字符串example.com
?
Right now, if I use window.location.hostname
– or location.hostname
– the return value is现在,如果我使用
window.location.hostname
– 或location.hostname
– 返回值是example.com
/
, but I want example.com
/
,但我想要example.com
, without the trailing slash. example.com
,没有尾部斜杠。
This question is similar to @ r1853 's “ How to remove trailing slash from window.location.pathname ”, but because JavaScript provides many ways to grab parts of a URI ( location.hostname
, location.host
, location.href
), and because wellformed URIs are a closed class, I had assumed there was a less expensive option than using a regular expression to remove trailing slashes from them.这个问题类似于@ r1853的“ How to remove trailing slash from window.location.pathname ”,但是因为 JavaScript 提供了很多方法来获取 URI 的一部分(
location.hostname
, location.host
, location.href
),并且因为格式正确的 URI 是一个封闭的类,所以我认为有一个比使用正则表达式从它们中删除尾部斜杠更便宜的选择。
Just put your window.location.hostname
into a variable:只需将您的
window.location.hostname
放入一个变量中:
let hostname = window.location.hostname;
and then use substring
to remove the last character (which will be that trailing slash)然后使用
substring
删除最后一个字符(这将是尾部斜杠)
hostname = hostname.substring(0, hostname.length - 1);
If you want to make sure that the last character is actually a /
, then you can use an if
statement:如果要确保最后一个字符实际上是
/
,则可以使用if
语句:
if (hostname.charAt(hostname.length - 1) == '/') {
hostname = hostname.substring(0, hostname.length - 1)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.