简体   繁体   中英

RegExp javascript match any word

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!

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');

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM