Recipe 3.2

Removing Query Parameters From a URL

You can use a URLSearchParams’s delete method to delete a query parameter. Or, to delete all parameters, you can set the URL’s search property to an empty string.

Enter a URL with some query parameters in the URL field. To remove a single parameter, enter the parameter name in the “Parameter to remove” field, then click “Remove Single Parameter”.

To remove all query parameters from the URL, click “Remove All Parameters”.

Demo

Code

JavaScript
/**
 * Removes a single parameter from an input URL.
 * 
 * @param inputUrl a URL string containing query parameters
 * @param paramName the name of the parameter to remove
 * @returns a new URL string with the given query parameter removed
 */
function removeQueryParameter(inputUrl, paramName) {
  console.log({ inputUrl, paramName });
  const url = new URL(inputUrl);
  url.searchParams.delete(paramName);
  return url.toString();
}

/**
 * Removes all parameters from an input URL.
 * 
 * @param inputUrl a URL string containing query parameters
 * @returns a new URL string with all query parameters removed
 */
function removeAllQueryParameters(inputUrl) {
  const url = new URL(inputUrl);
  url.search = '';
  return url.toString();
}

const form = document.querySelector('#url-form');
const removeButton = document.querySelector('#remove-single');
const removeAllButton = document.querySelector('#remove-all');

removeButton.addEventListener('click', () => {
  const url = form.elements.url.value;
  const param = form.elements.param.value;
  const newUrl = removeQueryParameter(url, param);
  renderResult(newUrl);
});

removeAllButton.addEventListener('click', () => {
  const newUrl = removeAllQueryParameters(form.elements.url.value);
  renderResult(newUrl);
});

function renderResult(newUrl) {
  const result = document.querySelector('#result');
  result.querySelector('#result-url').textContent = newUrl;
  result.classList.remove('d-none');
}
HTML

<div id="result" class="alert alert-primary d-none" role="alert">
  <h4>New URL</h4>
  <code id="result-url"></code>
</div>
<form id="url-form">
  <div class="mb-3">
    <label for="url" class="form-label">URL</label>
    <input type="url" class="form-control" id="url" value="https://example.com/api/users?status=active&role=admin">
  </div>
  <div><label for="param" class="form-label">Parameter to remove</label></div>
  <div class="input-group mb-3">
    <input type="text" class="form-control" value="status" id="param">
    <button class="btn btn-outline-secondary" type="button" id="remove-single">Remove Single Parameter</button>
  </div>
  <button class="btn btn-danger" id="remove-all" type="button">Remove All Parameters</button>
</form>
Web API Cookbook
Joe Attardi