自定义404页面

I have the following javascript code, I redirect old link to a new one dynamically.

Sometimes newLink does not exist, and instead of getting 404 page, I want to custom my own page if URL was not found.

Any idea how to add this condition in my code please ?

<script>
setTimeout(function(){
 $('a[href="oldLink"]').attr('href','dir/newLink)
 }, 1000);
</script>

EDIT : I am running this code on Rstudio, I am new to javascript, I don't have a server because I am producing HTML pages using Rmarkdown locally.

Thanks !

You can achieve it by the following code. There is one drawback that you have to always check if the link exist or not, if it is ok for you then this is the perfect solution for you.

$('body').append('<div id="temp-div" style="display:none"></div>');
    var url = 'dir/newLink';
    $('#temp-div').load(url, function (a, b, c) {
    if (c.status == 404)
        $('a[href="oldLink"]').attr('href', 'YOUR_CUSTOM_404_LINK');
    else
       $('a[href="oldLink"]').attr('href', url);
    $('#temp-div').remove();
});