Nice programing

해시가없는 자바 스크립트 창 위치 href?

nicepro 2020. 10. 31. 10:05
반응형

해시가없는 자바 스크립트 창 위치 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 ()하려고합니까?


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,"")


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

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

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

// Returns #hash

location.href.replace(location.hash,"")

더 짧은 솔루션 :

  • 쿼리 문자열과 해시없이 location.href.split(location.search||location.hash||/[?#]/)[0]

  • 해시없이 location.href.split(location.hash||"#")[0]

(보통 첫 번째를 사용합니다)


보편적 인 방법도 더 작습니까?

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

참고 URL : https://stackoverflow.com/questions/5818269/javascript-window-location-href-without-hash

반응형