title: Removing final part of URL in Javascript/Jquery
body: <p>I have some URL's that all follow the same structure.</p>
  
  <p><code>https://www.website.com/services/county/town/servicename/brand/</code></p>
  
  <p>When the search has zero results we display a button that when clicked runs a function to remove the final section of the URL and thus expand the search. </p>
  
  <p>For example if the above URL returned 0 results then clicking our button would load <code>https://www.website.com/services/county/town/servicename/</code> having removed <code>brand</code> from the search criteria and expanding the chance of results.</p>
  
  <p>The code I currently have for this works but seems like a bit of a hack.</p>
  
  <pre><code>function expandSearch() {
      var currentURL = window.location.href;
      var parts = currentURL.split("/");
      var lastPart;
  
      if ( parts.length === 9 )  {
          lastPart = currentURL.substr(currentURL.lastIndexOf('/') - parts[7].length) + '$';
          window.location.href = currentURL.replace( new RegExp(lastPart), "");
      } else if ( parts.length === 8 ) {
          lastPart = currentURL.substr(currentURL.lastIndexOf('/') - parts[6].length) + '$';
          window.location.href = currentURL.replace( new RegExp(lastPart), "");
      } else if ( parts.length === 7 ) {
          lastPart = currentURL.substr(currentURL.lastIndexOf('/') - parts[5].length) + '$';
          window.location.href = currentURL.replace( new RegExp(lastPart), "");
      } else if ( parts.length === 6 ) {
          lastPart = currentURL.substr(currentURL.lastIndexOf('/') - parts[4].length) + '$';
          window.location.href = currentURL.replace( new RegExp(lastPart), "");
      }
  }
  </code></pre>
  
  <p>The search can return 0 results at any point down to <code>https://www.website.com/services/</code> at which point the whole database is returned.</p>
  
  <p>The URL can also have missing elements for example it might have a <code>county</code> but no <code>town</code>.</p>
  
  <p>Is there a better/cleaner way of removing the final URL element and redirecting the browser to this new broader search?</p>
  
  <hr>
  
  <p>The final working version I ended up with thanks to @ebilgin for anyone looking:</p>
  
  <pre><code>function expandSearch() {
  
      var parts = window.location.pathname.substr(1).split("/");
      parts = parts.filter(Boolean); // Remove trailing empty array object
      parts.pop(); // Remove last array object
      window.location.href = "/" + parts.join("/") + "/"; // Go to new Location
  
  }
  </code></pre>