-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-
  • 218,210
  • 55
  • 464
  • 476
Harshal
  • 3,562
  • 9
  • 36
  • 65
  • 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
  • 2,084
  • 1
  • 19
  • 22
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
  • 28,279
  • 5
  • 35
  • 57
0

Use split in javascript

    var str = "http://example.com#question_1";
    
    alert(str.split("#")[0]);
Sudharsan S
  • 15,336
  • 3
  • 31
  • 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,593
  • 16
  • 73
  • 124
0

This will clear the id selector from the uri

location.hash = '';
  • 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,743
  • 8
  • 43
  • 69