2013-05-04 8 views
34

ho questo:ottenere il percorso e la stringa di query da URL utilizzando JavaScript

http://127.0.0.1:8000/found-locations/?state=--&km=km 

voglio che questo:

found-locations/?state=--&km=km 

come faccio a fare questo in javascript?

ho cercato window.location.href ma mi sta dando tutta l'url
ho provato window.location.pathname.substr(1) ma mi sta dando found-locations/

+0

Vedere questa domanda: http://stackoverflow.com/questions/441755/ regular-expression-to-remove-hostname-and-port-from-url – thebreiflabb

risposta

61

Usa location.pathname e location.search:

(location.pathname+location.search).substr(1) 
+0

Qual è il supporto del browser per questo, ho trovato: https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/search –

+0

Cos'è ' .substr (1) 'per? –

+1

@AmitTripathi il '.substr (1)' serve per rimuovere la barra all'inizio – Frankusky

5

URI.js è una bella libreria JavaScript per l'analisi di URI. Può fare ciò che hai richiesto con una bella sintassi fluente.

26
window.location.pathname + window.location.search 

si arriva l'URL di base /found-locations più la stringa di query ?state=--&km=km