5

How to replace a url like this

http://test.com/#part1

to:

http://test.com/part1

I know location.hash but it will detect if there is a hash in url.

poporo
  • 51
  • 1
  • 1
  • 2
  • Possible duplicate of [How to remove the hash from window.location (URL) with JavaScript without page refresh?](https://stackoverflow.com/questions/1397329/how-to-remove-the-hash-from-window-location-url-with-javascript-without-page-r) – PayteR Sep 10 '17 at 12:52

4 Answers4

8
location.href = location.href.replace(location.hash,location.hash.substr(1))
Joseph Marikle
  • 76,418
  • 17
  • 112
  • 129
1

You can use replace()

Here's a broken down version using windows.location:

var new_url = window.location.protocol + '//'
            + window.location.hostname + '/'
            + window.location.pathname + '/'
            + window.location.hash.replace('#','','g') ;

Or remove all the hashes:

var new_url = (window.location + '').replace('#','','g');
vol7ron
  • 40,809
  • 21
  • 119
  • 172
0
var file = location.pathname.substring(location.pathname.lastIndexOf("/") + 2);
var location = window.origin + "file";
window.location = location;
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

in my opinion is using regex replace on string best and cleanest solution

.replace( /#.*/, "");

example

location.href = location.href.replace( /#.*/, "");
PayteR
  • 1,727
  • 1
  • 19
  • 35
  • This is a duplicate of the original answer published 7 years ago. You should improve this or delete it since it adds no value as it is. – Mrchief Jul 23 '18 at 14:32