2011-08-05 42 views
3

如何更換URL這樣如何更換散列URL

http://test.com/#part1 

到:

http://test.com/part1 

我知道的location.hash,但如果在URL中的散列它將檢測。

下面是使用windows.location一個細分版本

window.location.pathname.replace('#', ''); 
+0

的可能的複製[如何刪除了window.location(URL)的散列沒有頁面刷新的JavaScript?](https://stackoverflow.com/questions/1397329/how-to-remove-the-hash-from-window-location-url-with-javascript-without-page-r) – PayteR

回答

1

試試這個

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

或刪除全部的哈希值:

var new_url = (window.location + '').replace('#','','g'); 
+0

nothig發生:( – poporo

+1

那是因爲location.pathname排除了散列...你應該使用location.href –

6
location.href = location.href.replace(location.hash,location.hash.substr(1)) 
+0

完美!謝謝。 – poporo

+0

不客氣:)高興地幫忙。 –

1

您可以使用替換():

0
var file = location.pathname.substring(location.pathname.lastIndexOf("/") + 2); 
var location = window.origin + "file"; 
window.location = location; 
0
在我看來

是使用正則表達式的字符串替換最好和乾淨的解決方案

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

例如

location.href = location.href.replace(/#.*/, "");