-1

I want to remove the hash, as well as anything after it, from a URL. For example, I might have:

http://example.com/#question_1

… which slides to question no. 1 to show an error message. When the user’s input then passes validation, I need to remove #question_1 from the current location.

I’ve tried all of these, but none of them has worked for me:

  • document.location.href.replace(location.hash, "");
  • window.location.hash.split('#')[0];
  • window.location.hash.substr(0, window.location.hash.indexOf('#'));

Note: I don’t just want to get the URL – I want to remove it from my address bar.

Ry-
  • 209,133
  • 54
  • 439
  • 449
Harshal Mahajan
  • 3,450
  • 8
  • 36
  • 68
  • 1
    What is `http://example.com#question_1`? currently loaded url? – MysticMagicϡ Sep 26 '14 at 10:56
  • See also here: http://stackoverflow.com/questions/4508574/remove-hash-from-url – algorhythm Sep 26 '14 at 10:58
  • possible duplicate of [How to remove the hash from window.location with JavaScript without page refresh?](http://stackoverflow.com/questions/1397329/how-to-remove-the-hash-from-window-location-with-javascript-without-page-refresh) – Cerbrus Sep 26 '14 at 10:59

6 Answers6

7
history.pushState("", document.title, window.location.href.replace(/\#(.+)/, '').replace(/http(s?)\:\/\/([^\/]+)/, '') )
Hereblur
  • 1,926
  • 19
  • 21
0

Try this :use .split() to split string by # and then read first element in array using index 0

    var url = 'http://example.com#question_1';
    var urlWithoutHash = url.split('#')[0];
    alert(urlWithoutHash );
Bhushan Kawadkar
  • 27,908
  • 5
  • 34
  • 57
0

Use split in javascript

    var str = "http://example.com#question_1";
    
    alert(str.split("#")[0]);
Sudharsan S
  • 15,058
  • 3
  • 28
  • 49
0

Try this way:

var currentPath = window.location.pathname;
var myUrl = currentPath.split("#")[0];

OR

var currentPath = window.location.href;
var myUrl = currentPath.split("#")[0];

Hope it helps.

MysticMagicϡ
  • 28,305
  • 16
  • 71
  • 119
0

This will clear the id selector from the uri

location.hash = '';
James Richford
  • 134
  • 2
  • 7
  • You can't get rid of the hash without reloading the page I think this would be the closest to actually remove it from the address bar :) – James Richford Sep 26 '14 at 11:03
0

Use .split as shown :

var str = "http://example.com#question_1";

alert((str.split("#")[0]);

or use .substring() as shown :

var str = "http://example.com#question_1";

alert((str.substring(0,str.indexOf('#'))));
Kartikeya Khosla
  • 18,495
  • 8
  • 42
  • 66