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 .
Asked
Active
Viewed 1.4k times
5
-
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 Answers
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
-
-
-
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
-
-
@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