JS Web Dev Web Frontend

JS Get Query String In URL

September 16, 2019

Handy way to get query string value in URL

Example URL: https://www.example.com/index?query1=result1&query2=result2

const params = new URLSearchParams(window.location.search);

// window.location.search is showing ?query1=result1&query2=result2
// then we can use the params.get('{paramName}') for getting the query param

console.log(params.get('query1')) // result: result1
console.log(params.get('query2')) // result: result2

For note: The query string value must be without hash (#). Try it to see what’s the problem.

Ref: https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/search