简体   繁体   中英

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 ?

Right now, if I use window.location.hostname – or location.hostname – the return value is
example.com / , but I want
example.com , without the trailing slash.


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.

Just put your window.location.hostname into a variable:

let hostname = window.location.hostname;

and then use substring to remove the last character (which will be that trailing slash)

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 (hostname.charAt(hostname.length - 1) == '/') {
  hostname = hostname.substring(0, hostname.length - 1)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM