如何返回不带斜杠的location.hostname?

问题描述 投票:-1回答:1

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

现在,如果我使用window.location.hostname –或location.hostname –返回值为example.com [/,但我想要example.com,但不带斜杠。

javascript string data-manipulation window.location trailing-slash
1个回答
0
投票

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

例如:

let hostname = window.location.hostname;

然后使用子字符串删除最后一个字符(将是结尾的逗号)

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

如果要确保最后一个字符是/,则可以始终放置以下if语句

if(hostname.charAt(hostname.length - 1) == '/') {
    hostname = hostname.substring(0, hostname.length - 1);
}
© www.soinside.com 2019 - 2024. All rights reserved.