Change URL Query Parameters as You Type in JavaScript

Hi devs in this quick example i will discuss about add query parameter to url javascript. Sometime you know that we need to change query params without reload in your application. So how we can do that?

In this quick example i am going to show you dynamically add parameter to url javascript. So if you don't know how to javascript change url parameter value then this example tutorial is for you.

Let's see the example code:

const searchInput = document.getElementById("search-input");

searchInput.addEventListener("keyup", function(event) {
    let searchParams = new URLSearchParams(window.location.search);

    searchParams.set("q", event.target.value);

    if (window.history.replaceState) {
        const url = window.location.protocol 
                    + "//" + window.location.host 
                    + window.location.pathname 
                    + "?" 
                    + searchParams.toString();

        window.history.replaceState({
            path: url
        }, "", url)
    }
});

 

Hope it can help you.

 

Facebook Github
A web enthusiastic, self-motivated Full-Stack Web Developer from Dhaka, Bangladesh with experience in developing applications using Laravel Vue and React Js Application.