2010-07-16 10 views
6

ho comeJavascript: ottieni window.location tutto tranne l'host?

http://www.mydomain.com/hello/you

con top.location.host, posso ottenere "http://www.mydomain.com"

con window.location.href posso ottenere "http://www.mydomain.com/hello/you"

c'è la possibilità di ottenere solo "/hello/you" ???

+0

Cosa potrebbe avere a che fare con jQuery? –

+0

Anurag: mentre stai modificando potresti anche liberarti della chiamata 'toString' ridondante su' location.host'. –

+0

yikes @no, ho sovrascritto mentre stavi cambiando? – Anurag

risposta

15
location.pathname 

pathname sarà solo restituire il percorso. Se si desidera querystring e facoltativamente hash, sarà necessario combinare anche le proprietà search e hash. Considerate questo url:

http://www.example.com/path/to/glory?key=value&world=cup#part/of/page 

location.pathname => "/path/to/glory" 
location.search => "?key=value&world=cup" 
location.hash  => "#part/of/page" 

Se si desidera che l'intera cosa,

/path/to/glory?key=value&world=cup#part/of/page 

poi basta concatenare tutti questi:

location.pathname + location.search + location.hash 

Sempre voluto utilizzare with da qualche parte. Questo appare come l'occasione perfetta :)

with(location) { 
    pathname + search + hash; 
} 
+0

Non dimenticare 'search' e' hash'. –

+0

@Matthew - la querystring o l'hash non erano elencati nella domanda dell'OP, quindi non posso presumere che lo vorrà, ma quello che posso fare è elaborare la mia risposta :) – Anurag

0

Un altro approccio sarebbe escluso il protocollo e host da tutto il href tramite stringa.

window.location.href.substring(
    (window.location.protocol+'//'+window.location.host).length 
) 

Se l'URL è http://google.com/test?whatever=1#hello verrà restituito /test?whatever=1#hello.

Problemi correlati