Javascript 如何返回location.hostname而不带尾随斜杠?

Javascript 如何返回location.hostname而不带尾随斜杠?,javascript,string,data-manipulation,window.location,trailing-slash,Javascript,String,Data Manipulation,Window.location,Trailing Slash,如果输入是https://example.com/page.html?query=string 现在,如果我使用window.location.hostname–或location.hostname–返回值是example.com/,但我希望example.com,后面没有斜杠 这个问题类似于@的“”,但因为JavaScript提供了许多获取URI部分的方法(location.hostname,location.host,location.href),并且因为格式良好的URI是一个封闭类,我假

如果输入是
https://example.com/page.html?query=string

现在,如果我使用
window.location.hostname
–或
location.hostname
–返回值是
example.com
/
,但我希望
example.com
,后面没有斜杠



这个问题类似于@的“”,但因为JavaScript提供了许多获取URI部分的方法(
location.hostname
location.host
location.href
),并且因为格式良好的URI是一个封闭类,我假设有一个比使用正则表达式从中删除尾部斜杠更便宜的选项。

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

让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)
}

这是否回答了您的问题?类似于,JavaScript中没有其他机制用于URI的这一部分,比如在Flash之前的
window.location.hostname等?我不知道