93

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/

1

6 Answers 6

129

Use location.pathname and location.search:

(location.pathname+location.search).substr(1)
Sign up to request clarification or add additional context in comments.

3 Comments

What is the browser support for this, I found: developer.mozilla.org/en-US/docs/Web/API/…
What is .substr(1) for?
@AmitTripathi the .substr(1) is to remove the slash at the start
62
window.location.pathname + window.location.search

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

Comments

18

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);

1 Comment

7

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

Comments

4

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

Comments

2
/**
 * @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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.