84

I have this:

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

I want this:

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

how do i do this in javascript?

I tried window.location.href but it is giving me whole url
I tried window.location.pathname.substr(1) but it is giving me found-locations/

Gumbo
  • 643,351
  • 109
  • 780
  • 844
doniyor
  • 36,596
  • 57
  • 175
  • 260
  • See this question: http://stackoverflow.com/questions/441755/regular-expression-to-remove-hostname-and-port-from-url – thebreiflabb May 04 '13 at 16:29

5 Answers5

116

Use location.pathname and location.search:

(location.pathname+location.search).substr(1)
Gumbo
  • 643,351
  • 109
  • 780
  • 844
58
window.location.pathname + window.location.search

Will get you the base url /found-locations plus the query string ?state=--&km=km

Sam R.
  • 16,027
  • 12
  • 69
  • 122
Miles Wilson
  • 851
  • 6
  • 4
14

If your url is a string, you can create URL object and use pathname and search property.

 let strurl = 'http://www.test.com/param1/param2?test=abc';
 let url = new URL(strurl)
 let pathandQuery = url.pathname + url.search;

let strurl = 'http://www.test.com/param1/param2?test=abc';
let url = new URL(strurl)
let pathandQuery = url.pathname + url.search;

console.log(pathandQuery);
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
7

get all path, query and even hash: location.href.replace(location.origin, '')

Iceberg
  • 2,744
  • 19
  • 19
4

URI.js is a nice JavaScript library for parsing URIs. It can do what you requested with a nice fluent syntax.