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

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

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 want to search your data source for data using parameters from the URL bar.

Note: 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.

The Markup

The markup for jQuery is similar, except that I’ll replace the onclick event with a class to each checkbox. You can also add unique ids to the checkboxes.

<body>
    <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>
The jQuery Method
<script>
    $(document).ready(function () {
        $(".chk").on("click", function () {
            window.location.replace('?price=' + $(this).val());
        });
    });
</script>

That’s it. Hope the example in this article is useful. Thanks for reading.

Related Posts:

Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.

Enter your email id

Delivered by FeedBurner
Tweet this article Facebook Google+
comments powered by Disqus

Join our Google Plus Community and be a part of a discussion!