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) {
  (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", searchBox_kqWNN.value);
window.history.pushState({}, "", xurl.toString());

JavaScript DOM, Get URL, Set URL