BoneStarr
BoneStarr

Reputation: 195

Insert Text String Into href Link (Specific Location)

I have links on a page that I wanted to add an ID Anchor too. This code I have works fine:

window.onload = function() {
    $('#main > div > ul > li > a').attr('href',function(i,str) {
         return str + '#myAnchor';
    });
};

But sometimes because of the way the page is set up tracking gets added to the links so what is happening at the moment is I get http://www.myurl.com/#someannoyingtracking#myAnchor which doesn't anchor. How can I insert the anchor in between the URL or always after the ".com/" Like this: http://www.myurl.com/#myAnchor#someannoyingtracking

Upvotes: 0

Views: 175

Answers (3)

dug
dug

Reputation: 2345

Piggybacking on Rick Hitchcock's answer, but regex-free:

$('#main > div > ul > li > a').each(function(index, elem) {
  elem.hash = '#myAnchor' + elem.hash;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
  <div>
    <ul>
      <li><a href="http://example.com/#someannoyingtracking">Has anchor</a>
      <li><a href="http://example.com/">No anchor</a>
    </ul>
  </div>    
</div>

Upvotes: 3

Clyff
Clyff

Reputation: 4076

You can use replace for that:

window.onload = function() {
    $('#main > div > ul > li > a').attr('href',function(i, str) {
        if (str.indexOf('#') > -1) {
            return str.replace('#', '#myAnchor');
        } else {
            return str + '#myAnchor';
        }
    });
};

Upvotes: 1

Rick Hitchcock
Rick Hitchcock

Reputation: 35680

This will insert an anchor before an annoying tracking anchor or at the end of the URL:

$('#main > div > ul > li > a').attr('href', function(i,str) {
  return str.replace(/(\#.+)|($)/, '#myAnchor$1');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
  <div>
    <ul>
      <li><a href="http://example.com/#someannoyingtracking">Has anchor</a>
      <li><a href="http://example.com/">No anchor</a>
    </ul>
  </div>    
</div>

Upvotes: 3

Related Questions