Get path and query string from URL using javascript
Asked Answered
F

6

90

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/

Fillet answered 4/5, 2013 at 16:25 Comment(1)
See this question: #442255Ibis
S
124

Use location.pathname and location.search:

(location.pathname+location.search).substr(1)
Scribe answered 4/5, 2013 at 16:30 Comment(3)
What is the browser support for this, I found: developer.mozilla.org/en-US/docs/Web/API/…Blouson
What is .substr(1) for?Firepower
@AmitTripathi the .substr(1) is to remove the slash at the startHatshepsut
T
59
window.location.pathname + window.location.search

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

Teneshatenesmus answered 4/5, 2013 at 16:31 Comment(0)
L
17

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);
Licking answered 2/7, 2019 at 4:12 Comment(1)
Not supported by IESpinks
B
7

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

Biltong answered 7/11, 2020 at 10:19 Comment(0)
S
4

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

Secretarial answered 4/5, 2013 at 16:29 Comment(0)
H
0
/**
 * @returns The path and query string (and possibly the hash fragment) of the current URL.
 */
export const getRelativeUrl = (url: string): string => {
  const urlObject = new URL(url);

  return `${urlObject.pathname}${urlObject.search}${urlObject.hash}`;
};

The cleanest version for getting relative URL.

Heidi answered 29/2, 2024 at 20:55 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.