Hi! I was looking for a simple search and highlight code and I found this one:
- $(function(){
- function searchAndHighlight(searchTerm, selector) {
- if(searchTerm) {
- //var wholeWordOnly = new RegExp("\\g"+searchTerm+"\\g","ig"); //matches whole word only
- //var anyCharacter = new RegExp("\\g["+searchTerm+"]\\g","ig"); //matches any word with any of search chars characters
- var selector = selector || "#bodyContainer"; //use body as selector if none provided
- var searchTermRegEx = new RegExp(searchTerm,"ig");
- var matches = $(selector).text().match(searchTermRegEx);
- if(matches) {
- $('.highlighted').removeClass('highlighted'); //Remove old search highlights
- $(selector).html($(selector).html().replace(searchTermRegEx, "<span class='match'>"+searchTerm+"</span>"));
- $('.match:first').addClass('highlighted');
- $('#next').on('click',i=1, function()
- { $('.match').removeClass('highlighted'); $('.match').eq(i).addClass('highlighted');
- if( i >= $('.match').length -1) {
- i=0;
- }
- i=i+1;
- });
- if($('.highlighted:first').length) { //if match found, scroll to where the first one appears
- $(window).scrollTop($('.highlighted:first').position().top);
- }
- return true;
- }
- }
- return false;
- }
- $(document).ready(function() {
- $('#search-button').on("click",function() {
- if(!searchAndHighlight($('#search-term').val())) {
- alert("No results found");
- }
- });
- });
- });//]]>
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:
- <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!