0

Hey all i have found the following code that finds a word within the page:

JSFiddle & Original Page

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 || "body";                             //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='highlighted'>"+searchTerm+"</span>"));
            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");
        }
    });
});

Within the code you can see it has var anyCharacter = new RegExp("\g["+searchTerm+"]\g","ig"); //matches any word with any of search chars characters.

However, when i try using that RegExp like so:

var searchTermRegEx = new RegExp("\\g["+searchTerm+"]\\g","ig");

it doesnt seem to return any results then even if i type in an exact name.

Any help would be great!

StealthRT
  • 10,108
  • 40
  • 183
  • 342
  • This might help you out http://stackoverflow.com/questions/9794851/find-text-string-in-jquery-and-make-it-bold/9795091#9795091 – elclanrs Dec 15 '13 at 22:27

2 Answers2

1

This fiddle works.

Not sure what the original authors were thinking with the \\g stuff.

The key is this regex:

      searchRegex   = new RegExp('(\\b)(' + searchTerm + ')(\\b)','ig');
Michael Mikowski
  • 1,269
  • 1
  • 10
  • 21
0

To match any word, try

/^\b\w+\b$/i

The regexp matches multiple characters between word boundaries

Replace

var searchTermRegEx = new RegExp("\\g["+searchTerm+"]\\g","ig");

with

var searchTermRegEx = /^\b\w+\b$/i;

The difference is that we are using regex literal than using regex object.