Luna Tech

Tutorials For Dummies.

Change URL (2 ways)

2022-05-14


1. Change URL and reload the page

Reference

// e.g., 
// input URL: https://lunawen.com?term=2022
// output URL: https://lunawen.com
// this approach will reload the page
const parsedUrl = new URL(window.location.href);
var index = parsedUrl.href.indexOf("?term=");
var cleanedUrl = parsedUrl.href.substring(0, index);
window.location.replace(new URL(cleanedUrl));

1. Change URL without reloading the page

Reference

// syntax
pushState(state, unused)
pushState(state, unused, url)
// e.g., 
// input URL: https://lunawen.com?term=2022
// output URL: https://lunawen.com
// this approach will not reload the page
var cleanedUrl = new URL(window.location);
cleanedUrl.searchParams.delete('term');
window.history.pushState(null, '', cleanedUrl.toString().replace("?", ''));