web-dev-qa-db-ja.com

ハッシュなしのjavascriptウィンドウの位置href?

私は持っています:

var uri = window.location.href;

それはhttp://example.com/something#hashを提供します

#hashなしでパス全体を取得する最良かつ最も簡単な方法は何ですか?

uri    = http://example.com/something#hash
nohash = http://example.com/something

すべてのブラウザで機能しないlocation.Origin+location.pathnameを使用してみました。私はlocation.protocol+'//'+location.Host+location.pathnameを使用してみましたが、これは私にとってはくだらない解決策のようなものです。

そのための最良かつ最も簡単な方法は何ですか?たぶん、location.hashを照会し、uriからこれをsubstr()しようとしますか?

69
matt

_location.protocol+'//'+location.Host+location.pathname_は、ポート番号またはクエリ文字列を気にしない場合の正しい構文です

気にするなら:

https://developer.mozilla.org/en/DOM/window.location

_location.protocol+'//'+
  location.Host+
  location.pathname+
 (location.search?location.search:"")
_

または

_location.protocol+'//'+
  location.hostname+
 (location.port?":"+location.port:"")+
  location.pathname+
 (location.search?location.search:"")
_

location.href.replace(location.hash,"")を実行することもできます

73
mplungjan
var uri = window.location.href.split("#")[0];

// Returns http://example.com/something

var hash = window.location.href.split("#")[1];

// Returns #hash
70
Nick Brunt
location.href.replace(location.hash,"")
13
Quentin

普遍的な方法も小さいですか?

location.href.split(/\?|#/)[0]
6
Alain Beauvois

より短いソリューション:

  • クエリ文字列とハッシュなしlocation.href.split(location.search||location.hash||/[?#]/)[0]

  • ハッシュなしlocation.href.split(location.hash||"#")[0]のみ

(通常、最初のものを使用します)

6
Sebastien P.