【问题标题】:RegExp javascript match any wordRegExp javascript匹配任何单词
【发布时间】:2013-12-15 22:15:57
【问题描述】:

大家好,我发现以下代码可以在页面中找到一个单词:

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");
        }
    });
});

在代码中你可以看到它有 var anyCharacter = new RegExp("\g["+searchTerm+"]\g","ig"); //匹配任何带有任何搜索字符的单词

但是,当我尝试像这样使用 RegExp 时:

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

即使我输入了确切的名称,它似乎也不会返回 任何 结果。

任何帮助都会很棒!

【问题讨论】:

标签: javascript regex match


【解决方案1】:

这个fiddle 有效。

不确定原始作者对 \\g 的想法是什么。

关键是这个正则表达式:

      searchRegex   = new RegExp('(\\b)(' + searchTerm + ')(\\b)','ig');

【讨论】:

  • 不确定您的小提琴是否有效?如果你输入 ace 它说它找不到它.. 即使 space 里面有 ace
  • 也许我看错了。我正在寻找一种 wildcard 类型,就像您在 SQL 查询中找到的那样 %whateverHere%.
  • 啊,我误会了。该解决方案只能找到整个单词。给我一点时间来匹配部分......见jsfiddle.net/wmca4/5
  • 我还注意到,如果您搜索过一次,然后再次尝试搜索,它什么也没做?
  • 是的,小提琴仅限于一次搜索。我很确定它和原来的小提琴是一样的。
【解决方案2】:

要匹配任何单词,请尝试

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

正则表达式匹配单词边界之间的多个字符

替换

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

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

区别在于我们使用的是正则表达式文字而不是使用正则表达式对象。

【讨论】:

  • 开始和结束字符加上全局标志在这里没有多大意义。
  • 对是否包含它感到困惑。固定。
  • @aliasm2k 我的 OP 中的代码会放在哪里?你可以在代码示例中使用它吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-21
  • 2012-06-22
  • 1970-01-01
  • 2019-07-25
  • 2011-08-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多