5

Is it possible to automatically change the url example.com/4000/title-2/#!4000 to example.com/4000/title-2 without to refresh the page ? Basically to remove "/#!4000" from the URL. Note that is important to remove the "/" before the hashbang not just the hashbang .

Knu
  • 14,806
  • 5
  • 56
  • 89
themihai
  • 7,903
  • 11
  • 39
  • 61
  • Automatically or programmatically? – Sergio Tulentsev Apr 21 '12 at 17:37
  • You want to change..? The `href` of a link element, or `window.location`? I'd suggest, if you want to change the URL in the browser's address-bar, that you look at url-rewriting, with whatever you've got running on your server (Apache?). – David Thomas Apr 21 '12 at 17:38

1 Answers1

12

dont know if it is enough for you and whether it works completely cross-browser... chrome accepts:

location.hash = "";

but this keeps the "#" in the address bar

in modern browsers that completely support the html5 history api you do:

window.history.replaceState('Object', 'Title', '/4000/title-2');

EDIT: this dies not change the history of the browser

EDIT 2: just found this stackoverflow resource

Community
  • 1
  • 1
Tobias Krogh
  • 3,768
  • 20
  • 14
  • we need to remove # and also the "/" before it . – themihai Apr 21 '12 at 17:40
  • @mihai it is impossible without a page refresh. – sg3s Apr 21 '12 at 17:44
  • 3
    [MDN entry for browser history](https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history), and [W3 entry for `replaceState()`](http://www.w3.org/TR/html5/history.html#dom-history-replacestate). And +1 for awesome, I hadn't come across that before =) – David Thomas Apr 21 '12 at 17:49
  • I agree, HTML5 is offering awesome APIs :) – Tobias Krogh Apr 21 '12 at 18:01
  • @TobiasKrogh is it possible to do that without to know /4000/title-2 ? I know there may be a trick to get it from window.location but I'm wondering if can be done directly using a kind of "relative" path (e.g. "../") – themihai Apr 21 '12 at 18:01
  • checkout location.pathname (but there you might have the last "/" so you need to check and strip it on your own)... location pathname holds everything between the domain and the query respectively hash – Tobias Krogh Apr 21 '12 at 18:03
  • Is there anyway to do it without changing `state`? I don't want to lose my state that is being passed from `router.navigate` – Waleed Ahmad Apr 12 '23 at 08:34
  • 1
    @WaleedAhmad `router.navigate` sounds like you are in an Angular context? If so you might be able to fetch the current state using `getState()` via [Location](https://angular.io/api/common/Location) and pass that to the new entry using `replaceState()`... generally speaking it might make sense to use the Angular APIs rather than native ones here but that also depends on your router settings... does this help? – Tobias Krogh Apr 13 '23 at 09:14