Remove last forward slash from href anchor

2019-08-17 02:09发布

问题:

I have the following anchor situation:

<a href="https://example.com/my-account/#example/" class="anchor">...</a>

The above anchor gives me a jQuery conflict because of the slash of the # link. Because this is PHP generated I am looking for a jQuery Javascript solution to remove the last character of the href of this anchor. How do I do that?

The reason for this jquery conflict is, because #-links on my site are and should be scroll-to-id properties. So it scrolls to the id-element. This is a functionallity I cannot change how it's build, so the only solution I see is to remove the last / from the anchor.

回答1:

The above anchor gives me a jQuery conflict because of the slash of the #-link

I'd suggest that you should fix that conflict as there is nothing inherently wrong with having a / in the fragment of the URL. If it's causing an error for you, then you need to fix your logic.

That being said, it's possible to do what you require by passing a function to prop() which removes any trailing slashes using a regex:

$('.anchor').prop('href', function(i, href) {
  return href.replace(/\/$/, '');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<a href="https://example.com/my-account/#example/" class="anchor">...</a>



回答2:

You can use attr() method with a callback which iterates over the elements internally where callback holds old value as the second argument and it will update with the returned value.

$('.anchor').attr('href', (_, href) => href.slice(0, -1));

$('.anchor').attr('href', (_, href) => href.slice(0, -1));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="https://example.com/my-account/#example/" class="anchor">...</a>



回答3:

If you have to change it at the Javascript side, you could split the string, pop the last element off, and rejoin it... (this assumes that the last character will ALWAYS be /, you'll need a sanity check if this is not always the case).

let href = $('.anchor').prop('href').split("");
href.pop();
href = href.join("");

console.log(href); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="https://example.com/my-account/#example/" class="anchor">...</a>