JS DOM: Update URL Query String

By Xah Lee. Date: . Last updated: .

Problem Description

if you have a Input Text Field such as a search box, and you want user to be able to use the URL to fetch the same search result they typed in the search box.

Solution

make your code do 2 things:

Get the URL Parameter Value

here's how to get the url param values:

const searchBox_kqWNN = document.getElementById("searchBox_kqWNN");

{
  const xurlSearchStr = (new URLSearchParams(window.location.search));
  if (xurlSearchStr) {
    ((<HTMLInputElement> searchBox_kqWNN).value) = xurlSearchStr.get("q");
  }
}

Set the URL Parameter Value

here's how to get set url param values, from a search box value:

const xurl: URL = (new URL(window.location.toString()));
  xurl.searchParams.set("q", ((<HTMLInputElement> searchBox_kqWNN).value));
  window.history.pushState({}, "", xurl.toString());

JavaScript DOM, Get URL, Set URL