Problem using word search and highlight

Problem using word search and highlight

Hi! I was looking for a simple search and highlight code and I  found this one: 

  1. $(function(){
  2. function searchAndHighlight(searchTerm, selector) {
  3.     if(searchTerm) {
  4.         //var wholeWordOnly = new RegExp("\\g"+searchTerm+"\\g","ig"); //matches whole word only
  5.         //var anyCharacter = new RegExp("\\g["+searchTerm+"]\\g","ig"); //matches any word with any of search chars characters
  6.         var selector = selector || "#bodyContainer";                             //use body as selector if none provided
  7.         var searchTermRegEx = new RegExp(searchTerm,"ig");
  8.         var matches = $(selector).text().match(searchTermRegEx);
  9.         if(matches) {
  10.            $('.highlighted').removeClass('highlighted');     //Remove old search highlights
  11.                 $(selector).html($(selector).html().replace(searchTermRegEx, "<span class='match'>"+searchTerm+"</span>"));
  12.            $('.match:first').addClass('highlighted');
  13.             $('#next').on('click',i=1, function()
  14.         {                                                                   $('.match').removeClass('highlighted');                                                                   $('.match').eq(i).addClass('highlighted');
  15.          if( i >= $('.match').length -1) {
  16.              i=0;
  17.          }
  18.           i=i+1;  
  19.      }); 

  20.             if($('.highlighted:first').length) {             //if match found, scroll to where the first one appears
  21.                 $(window).scrollTop($('.highlighted:first').position().top);
  22.             }
  23.             return true;
  24.         }
  25.     }
  26.     return false;
  27. }
  28. $(document).ready(function() {
  29.     $('#search-button').on("click",function() {
  30.         if(!searchAndHighlight($('#search-term').val())) {
  31.             alert("No results found");
  32.         }
  33.     });
  34. });
  35. });//]]>  
It works fine when the url is not the same as the link description, but when they are, it adds the class to both url and link description, and the url gets broken.
Something like this:
  1. <a href="http://mywebsite.com/tagged/<span class='match'>back</span>"><span class="match highlighted">back</span></a>

Can somebody please help me? I've tried many solutions but none has worked. thanks in advance!