0

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.

Lucas
  • 523
  • 2
  • 10
  • 20
  • 1
    Does this answer your question? [How to remove trailing slash from window.location.pathname](https://stackoverflow.com/questions/31185383/how-to-remove-trailing-slash-from-window-location-pathname) – Mitya Dec 29 '19 at 21:08
  • Similar to https://stackoverflow.com/questions/31185383/how-to-remove-trailing-slash-from-window-location-pathname – Kwame Opare Asiedu Dec 29 '19 at 21:08

1 Answers1

3

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

brettwhiteman
  • 4,210
  • 2
  • 29
  • 38
Tom Truyen
  • 318
  • 1
  • 3
  • 15