-1

I want to know if there is a way to change a hashtag in a url using jQuery. For example, in the following tag,

<div class="comments"><a href="http://www.example.com/post/#comment">Link</a></div>

I want to change #comment to #response using jQuery.

How can I handle this case?

Thanks.

Peter
  • 692
  • 3
  • 10
  • 24
  • Possible duplicate of [possible to replace window.location.hash?](http://stackoverflow.com/questions/3377150/possible-to-replace-window-location-hash) – Derek Pollard Dec 09 '16 at 22:28
  • Be more specific about what you are trying to achieve. Do you just need to replace one URL? or do you need this to be flexible? – Jordan Soltman Dec 09 '16 at 22:28
  • `$('.comments > a:first').attr('href', $('.comments > a:first').attr('href').replace('comment', 'response');`? – Dom Dec 09 '16 at 22:32
  • @Dom. Thanks for your comment. I will try to use your code. – Peter Dec 10 '16 at 23:34
  • @Jordan S. Sorry. The Url will be dynamically changed. – Peter Dec 10 '16 at 23:35

1 Answers1

0

String.prototype.replace and jQuery's .attr will do the trick:

//Select the link
var link = $('a[href="http://www.example.com/post/#comment"]');
//Change the href attribute
link.attr('href', link.attr('href').replace('#comment', '#response'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="http://www.example.com/post/#comment">Link</a>
J. Titus
  • 9,535
  • 1
  • 32
  • 45