javascript new url

Javascript New URL

If you are working with JavaScript, there are times when you need to change the current URL of a webpage. This can be done using the 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:

window.location.replace('newURL');

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:

window.location.assign('newURL');

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.

For example:

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'.

Conclusion

Changing the URL of a webpage using JavaScript can be useful in many situations, such as implementing single-page applications or tracking user actions. You can use the 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.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe