The pathname of a URL is the string containing an initial "/" followed by the path of the URL. Or an empty string if there is no path in the URL.

How do you get the URL pathname value for a web page when coding in JavaScript?

JavaScript has a built-in way to get this information using the Location API interface, which represents the location (URL) of the current web page you're located on. The global Window interface has access to the Location object that can be used via window.location.

Using that interface, you can get the URL pathname with this method:

    
      window.location.pathname
    
  

This method will return a USVString containing an initial "/" character followed by the path of the URL.

Here are some example returned values to expect:

    
      // Page URL: https://coderrocketfuel.com/courses
      window.location.pathname == "/courses"

      // Page URL: https://coderrocketfuel.com/courses/build-a-coding-blog
      window.location.pathname == "/courses/build-a-coding-blog"

      // Page URL: https://coderrocketfuel.com
      window.location.pathname == "/"
      
      // Page URL: https://coderrocketfuel.com/courses/build-a-coding-blog?q=tacos
      window.location.pathname == "/courses/build-a-coding-blog"
    
  

Notice that a URL without a pathname will return a "/" string.

Also, if a URL has a query string (after the ? symbol), it will not be included in the returned pathname value.

To quickly test this, open the developer tools in your favorite browser and call the window.location.pathname function in the JavaScript console. The URL pathname should be logged to the console.

For more information on the browser support for this method, see its MDN web docs page.

Thanks for reading and happy coding!