javascript window location href without hash?
Mam:
var uri = window.location.href;
Który zapewnia http://example.com/something#hash
Jaki jest najlepszy i najłatwiejszy sposób na pokonanie całej ścieżki bez #hash
?
uri = http://example.com/something#hash
nohash = http://example.com/something
Próbowałem użyć location.origin+location.pathname
, który nie działa w każdej przeglądarce. Próbowałem użyć location.protocol+'//'+location.host+location.pathname
, co wygląda jak gówniane rozwiązanie dla mnie.
Jaki jest najlepszy i najłatwiejszy sposób, aby to zrobić? może pytam o lokalizację.hash i spróbuj substr () to z uri?
5 answers
location.protocol+'//'+location.host+location.pathname
jest poprawną składnią jeśli nie zależy ci na numerze portu lub querystring
If you do care:
Https://developer.mozilla.org/en/DOM/window.location
location.protocol+'//'+location.host+location.pathname+(location.search?location.search:"")
Lub
location.protocol+'//'+location.hostname+(location.port?":"+location.port:"")+location.pathname+(location.search?location.search:"")
Możesz też po prostu zrobić location.href.replace(location.hash,"")
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-21 14:00:38
var uri = window.location.href.split("#")[0];
// Returns http://example.com/something
var hash = window.location.href.split("#")[1];
// Returns #hash
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 20:00:22
location.href.replace(location.hash,"")
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-04-28 12:04:33
Krótsze rozwiązania:
Bez Łańcucha zapytania i hasha
location.href.split(location.search||location.hash||/[?#]/)[0]
Tylko bez haszu
location.href.split(location.hash||"#")[0]
(zwykle używam pierwszego)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-02-03 15:14:51
Czy uniwersalny sposób jest również mniejszy?
location.href.split(/\?|#/)[0]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-21 14:00:59