Get path and query string from URL using javascript

JavascriptUrlUri

Javascript Problem Overview


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/

Javascript Solutions


Solution 1 - Javascript

Use location.pathname and location.search:

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

Solution 2 - Javascript

window.location.pathname + window.location.search

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

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Solution 5 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondoniyorView Question on Stackoverflow
Solution 1 - JavascriptGumboView Answer on Stackoverflow
Solution 2 - JavascriptMiles WilsonView Answer on Stackoverflow
Solution 3 - JavascriptHien NguyenView Answer on Stackoverflow
Solution 4 - JavascriptIcebergView Answer on Stackoverflow
Solution 5 - JavascriptIvailo KaramanolevView Answer on Stackoverflow