0

I am a bit confused, because I just want to add a hash to an existing url via varibale and open it via a href.

Example:

$( ".MyLink" ).each( function(){
    var href = $(this).attr('href');
    $(this).attr("href", "https://website.com/subpage#" + href);
});

Result (browser url) after clicking on this link:

https://website.com/subpage/#test

If I am right, a correct hash link should look like this ...

https://website.com/subpage#test

... without the "/" after subpage.

So, I am correct or it doesn't matter? If yes, how can I change it?

I also realized that my browser(s) change my url from https://website.com/subpage#test to https://website.com/subpage/#test if I just add it in the browser bar and press enter. Is that new?

Maybe it is important to know that I use wordpress?

OK, it seemes to be a php/browser/wordpress rule that # become /#, because this script creates an endless refresh-loop for me:

var urlupdate = window.location.href.replace("/#", "#");
window.location.href = urlupdate;
Pepe
  • 960
  • 9
  • 21
  • Maybe take a look at this question: [When should I use a trailing slash in my URL?](https://stackoverflow.com/questions/5948659/when-should-i-use-a-trailing-slash-in-my-url) – A_A Oct 18 '20 at 12:41
  • Thx 4 the link, I will take a look ... – Pepe Oct 18 '20 at 12:56

1 Answers1

0

Update: As described in this answer, it shouldn't make a difference if your Javascript was written properly, it seems to be even considered as a best practice. If you want to get rid of it anyways you may want to check your wordpress settings, maybe the second answer of the given question may give you a hint!


In case that the trailing slash comes from the a tag, you could check whether the string in the href attribute starts with a slash and remove it then:

$( ".MyLink" ).each( function(){
    var href = $(this).attr('href');

    if (href.charAt(0) === '/') {
        href = href.substring(1, href.length);
    }

    $(this).attr("href", "https://website.com/subpage#" + href);
});
Alexander Belokon
  • 1,452
  • 2
  • 17
  • 37