HTML DOM의 Location replace() 메서드는 현재 문서를 새 문서로 대체하여 화면에 렌더링하는 데 사용됩니다. 이 메서드의 가장 큰 특징은 브라우저의 세션 히스토리에서 현재 문서의 URL을 제거한다는 점입니다. 따라서 페이지가 이동한 후에는 '뒤로 가기' 버튼을 눌러도 이전 문서로 돌아갈 수 없습니다.
구문
replace() 메서드의 기본 구문은 다음과 같습니다 −
location.replace(URLString)
URLString 매개변수에는 이동하고자 하는 새 문서의 URL을 문자열 형태로 전달합니다.
assign()과 replace()의 차이점
location.assign()은 히스토리에 기록을 남기므로 뒤로 가기 버튼으로 이전 페이지에 돌아올 수 있지만, location.replace()는 히스토리를 남기지 않아 뒤로 가기가 불가능합니다. 로그인 후 특정 페이지로 보내거나, 사용자가 이전 페이지로 되돌아가지 않기를 원하는 상황에서 replace()가 유용하게 활용됩니다.
예제
Location replace() 메서드의 실제 동작을 확인할 수 있는 예제입니다 −
<!DOCTYPE html>
<html>
<head>
<title>Location replace()</title>
<style>
form {
width:70%;
margin: 0 auto;
text-align: center;
}
* {
padding: 2px;
margin:5px;
}
input[type="button"] {
border-radius: 10px;
}
</style>
</head>
<body>
<form>
<fieldset>
<legend>Location-replace( )</legend>
<label for="urlSelect">Current URL: </label>
<input type="url" id="urlSelect" value="https://www.example.com"><br>
<label for="newUrlSelect">New URL: </label>
<input type="url" id="newUrlSelect" placeholder="Give new url..."><br>
<input type="button" onclick="doReplace()" value="Go to new URL">
<div id="divDisplay"></div>
</fieldset>
</form>
<script>
var divDisplay = document.getElementById("divDisplay");
var urlSelect = document.getElementById("urlSelect");
var newUrlSelect = document.getElementById("newUrlSelect");
function doReplace(){
if(newUrlSelect.value === '')
divDisplay.textContent = 'Provide new URL';
else{
location.replace(newUrlSelect.value);
divDisplay.textContent = 'Redirecting to new URL';
}
}
</script>
</body>
</html>
출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다 −
입력값이 비어 있는 상태에서 'Go to new URL' 버튼을 클릭한 경우, 'Provide new URL'이라는 안내 메시지가 표시됩니다 −

새 URL을 입력한 후 'Go to new URL' 버튼을 클릭하면 해당 URL로 리디렉션이 진행되며, 'Redirecting to new URL' 메시지가 출력됩니다 −
