'Delete part of an URL

I have some URLs in a menu that contain the whole path and end with an anchor (#anchor). That is nececessairy to jump from other parts of the website to the desired point In some cases (especially when I am already on that site that contains the ancors, I do not want to use the whole URL, I just need the end (#anchor). Like that I do not have a reload of the whole page and I can use a nice "sofrscroll".

In order to eliminate the unwanted part of the URL I have some code, but it does not work the way I want. I can substitute the unwanted part of the URL with another term, but I cannot substitute it with an empty space. If I want to substitute it with an empty space, the URL is displayed two times.

OK,, here is the code that works partially:

        $('.sub-menu a').each(function(){ 
                var oldUrl = $(this).attr("href"); 
                var newUrl = oldUrl.replace("https://example.com/page1/", "h://"); 
                $(this).attr("href", newUrl); 
            }); 

That works well and it creates URLS like h://#anchor. Unfortunately these URLs cannot be used ;)

If I fry to substitute other code like this, it does not work:

        $('.sub-menu a').each(function(){ 
                var oldUrl = $(this).attr("href"); 
                var newUrl = oldUrl.replace("https://example.com/page1/", ""); 
                $(this).attr("href", newUrl); 
            }); 

Can anybody tell me, where is my mistake? Thanks!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source