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.
<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>
<script>
function replaceURL(chk) {
window.location.replace('?price=' + chk.value);
}
</script>
The method is quite similar if you are using jQuery instead of JavaScript. The result will be the same.
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>