Here are two ways to modify the URL without reloading the page in JavaScript.
- Using the replaceState() function
- Using the pushState() function
Method 1: Using the replaceState() function
The replaceState() function is “used to modify the current history entry and replace the properties of the state with ones in the passed parameters.”
<!DOCTYPE html>
<html>
<head>
<title>Replace State Demo</title>
<script type="text/javascript">
function changeUrl() {
history.replaceState({}, "", "/new-url");
document.getElementById('urlDisplay').innerHTML = window.location.href;
}
</script>
</head>
<body>
<h1 style="color: red;">Current URL:</h1>
<p id="urlDisplay"></p>
<button onclick="changeUrl()">Change URL</button>
<script type="text/javascript">
document.getElementById('urlDisplay').innerHTML = window.location.href;
</script>
</body>
</html>
Before clicking the button
After clicking the button
Method 2: Using the pushState() function
The pushState() method is “used to add a new history entry with the properties passed as parameters.” This function will change the current URL to the new URL without reloading the page.
<!DOCTYPE html>
<html>
<head>
<title>Push State Demo</title>
<script type="text/javascript">
function changeUrl() {
history.pushState({}, "", "/new-url");
document.getElementById('urlDisplay').innerHTML = window.location.href;
}
</script>
</head>
<body>
<h1 style="color: red;">Current URL:</h1>
<p id="urlDisplay"></p>
<button onclick="changeUrl()">Change URL</button>
<script type="text/javascript">
document.getElementById('urlDisplay').innerHTML = window.location.href;
</script>
</body>
</html>
Before clicking the button
After clicking the button
That’s it.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.