Recipe 3.4
Reading Query Parameters
Individual query parameters can be read using the URL’s searchParams
property, which is a URLSearchParams
object.
This object has a forEach
function to iterate over all key-value pairs, which can be used to get a list of all query parameters.
Enter a URL containing some parameters, and click the “Parse URL” button. A table will be shown with the parameter keys and values.
Demo
Name | Value |
---|
Code
JavaScript
/**
* Takes a URL and returns an array of its query parameters.
*
* @param inputUrl A URL string
* @returns An array of objects with key and value properties
*/
function getQueryParameters(inputUrl) {
// Can't use an object here because there may be multiple
// parameters with the same key, and we want to return all parameers.
const result = [];
const url = new URL(inputUrl);
// Add each key/value pair to the result array
url.searchParams.forEach((value, key) => {
result.push({ key, value });
});
// Results are ready!
return result;
}
const form = document.querySelector('#url-form');
form.addEventListener('submit', event => {
event.preventDefault();
const table = document.querySelector('#query-params');
const tableBody = document.querySelector('#query-params tbody');
// Remove the previous table rows.
tableBody.innerHTML = '';
const params = getQueryParameters(form.elements.url.value);
// For each key-value pair, render a row in the table.
params.forEach(param => {
const row = document.createElement('tr');
const nameCell = document.createElement('td');
nameCell.className = 'font-monospace';
nameCell.textContent = param.key;
row.append(nameCell);
const valueCell = document.createElement('td');
valueCell.className = 'font-monospace';
valueCell.textContent = param.value;
row.append(valueCell);
tableBody.appendChild(row);
});
// Show the table, if it was hidden.
table.classList.remove('d-none');
});
HTML
<form id="url-form">
<div class="mb-3">
<label for="url" class="form-label">URL</label>
<input type="url" class="form-control" id="url" name="url" value="https://example.com/api/users?status=active&role=admin&role=user&limit=100">
</div>
<button class="btn btn-primary">Parse URL</button>
</form>
<table id="query-params" class="mt-3 table d-none">
<thead>
<tr>
<th class="w-25">Name</th>
<th class="w-25">Value</th>
</tr>
</thead>
<tbody></tbody>
</table>