Get path and query string from URL using javascript

Solution 1:

Use location.pathname and location.search:

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

Solution 2:

window.location.pathname + window.location.search

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

Solution 3:

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