If you are working with browsers that support the HTML5 History API, you could use replaceState:
$(document).ready(() => {
var redirectUrl = _spPageContextInfo.webAbsoluteUrl + "/" + _spPageContextInfo.layoutsUrl + "/Redirect.aspx";
var queryParameters = {}, queryString = location.search.substring(1), re = /((^&=)+)=((^&)*)/g, m;
while (m = re.exec(queryString)) {
queryParameters(decodeURIComponent(m(1))) = decodeURIComponent(m(2));
}
queryParameters('Source') = redirectUrl;
var updatedParams = location.search.replace(location.search, $.param(queryParameters));
if (history.replaceState) {
var newurl = window.location.origin + window.location.pathname + "?" + updatedParams;
window.history.replaceState({ path: newurl }, '', newurl);
}
});
However, if you are trying to modify the source on a form in SharePoint, that won’t be sufficient. Some onclick events are populated when the page loads with the initial Source value and these events will have to be override as well since they will redirect to the previous value:
$("#part1").on("click", "input(value='Cancel')", function (e) {
e.preventDefault();
window.location.href = redirectUrl;
});
$("#Ribbon.ListForm.Edit.Commit.Cancel-Large").click(function (e) {
e.preventDefault();
window.location.href = redirectUrl;
});