简体   繁体   English

RegExp javascript匹配任何单词

[英]RegExp javascript match any word

Hey all i have found the following code that finds a word within the page: 嘿,我发现以下代码在页面中找到了一个单词:

JSFiddle & Original Page JSFiddle原始页面

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"); 在代码中,您可以看到它具有var anyCharacter = new RegExp(“ \\ g [” + searchTerm +“] \\ g”,“ ig”); //matches any word with any of search chars characters . //将任何单词与任何搜索字符char匹配

However, when i try using that RegExp like so: 但是,当我尝试像这样使用RegExp时:

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. 不确定原始作者对\\\\ g东西的想法。

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. 区别在于我们使用的是正则表达式文字,而不是使用的是regex对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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