window.location object. You can use the
window.location.replace() method to replace the current URL with a new one. The syntax is as follows:
The above code will replace the current URL with 'newURL'. Remember to include the protocol (http or https) when specifying the new URL.
Another way to change the URL is to use the
window.location.assign() method. The syntax is similar:
The above code will also change the current URL to 'newURL'. However, unlike
replace(), it adds an entry in the browser's history stack, allowing the user to navigate back to the previous page using the back button.
If you want to change only a part of the URL, you can use the
history.pushState() method. This method allows you to change the URL without reloading the page. The syntax is as follows:
history.pushState(stateObject, title, URL);
stateObject: An object representing the state of the new page. This can be null if you don't need to store any data.
title: The new title of the page.
URL: The new URL. This can be a relative or absolute URL.
history.pushState(null, 'New Page Title', '/new-url');
The above code will change the URL to
/new-url and set the title of the page to 'New Page Title'.
window.location.replace() method to replace the current URL, the
window.location.assign() method to add a new entry in the browser's history stack, or the
history.pushState() method to change only a part of the URL without reloading the page.