How to Replace a String with another String in the URL Bar using JavaScript or jQuery

← PrevNext →

In one of my previous article, I have explained with an example on how to check if the URL bar contains a given string using JavaScript or jQuery . Now here in this article, I’ll show you how to replace the a given string with another string in the URL bar using the location.replace() method in JavaScript or jQuery.

Replace a String in the URL bar with another string using JavaScript or jQuery

See this demo

Syntax for replace() Method

object.replace(url)

The location.replace() method will replace the current URL with a new URL, which you will provide. In addition, you can replace the current URL’s parameters.

You will need this method if you are using the URL parameters to communicate with objects or elements on a web page. For example, you can search the database using the parameters from the URL bar.

Remember: If you are using the replace() method to replace the URL, the page will not be saved in the session history. This means, you cannot use the back button to navigate back to the previous page.

Now let’s see an example. I have few checkboxes on my web page and I wish to replace the URL address with the value of the checkbox that I’ll click. Often, online retail shops use this method to refine the search of their products.

The Markup
<body>
    <input type="checkbox" value="10" onclick="replaceURL(this)" /> 10$ <br />
    <input type="checkbox" value="20" onclick="replaceURL(this)" /> 20$ <br />
    <input type="checkbox" value="30" onclick="replaceURL(this)" /> 30$
</body>
The JavaScript Method
<script>
    function replaceURL(chk) {
        window.location.replace('?price=' + chk.value);
    }
</script>

See this demo

The method is quite similar if you are using jQuery instead of JavaScript. The result will be the same.

Using a jQuery Method

In this example too, I am using checkboxes, except that I’ll replace the onclick event by defining a class to each checkbox. You can also add unique ids to the checkboxes.

<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

    <input type="checkbox" value="10" class="chk" /> 10$ <br />
    <input type="checkbox" value="20" class="chk" /> 20$ <br />
    <input type="checkbox" value="30" class="chk" /> 30$
</body>

<script>
    $(document).ready(function () {
        $(".chk").on("click", function () {
            window.location.replace('?price=' + $(this).val());
        });
    });
</script>

← PreviousNext →