Get the full query string via the window.location.search
property. URLSearchParams is an inbuilt API to get query string parameters in JavaScript.
JavaScript get query string Example
HTML examples code:
Get Single Parameters
<!DOCTYPE HTML>
<html>
<body>
<script>
var url_string = "http://www.example.com/t.html?name=A&sal=3000&c=xyz";
var url = new URL(url_string);
var c = url.searchParams.get("c");
console.log(c);
</script>
</body>
</html>
Output:
Code for get the query string from the URL of the current page with:
// https://testsite.com/users?page=10&pagesize=25&order=asc
const urlParams = new URLSearchParams(window.location.search);
const pageSize = urlParams.get('pageSize');
Multiple Parameters use the for…of
The URLSearchParams is an iterable object, use the for…of structure to iterate over its elements which are query string parameters:
<!DOCTYPE HTML>
<html>
<body>
<script>
const site = new URL("https://test.com/hello?name=roger&age=20");
const params = new URLSearchParams(site.search);
for (const param of params) {
console.log(param)
}
</script>
</body>
</html>
Output:
Do comment if you have any doubts and suggestions on this JS URL topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version