javascriptstringdata-manipulationwindow.locationtrailing-slash

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.


Solution

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