2013-12-15 13 views
0

嘿所有我发现下面的代码,找到页面中的一个词:正则表达式的JavaScript匹配任何字

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 =新的RegExp(“\ g [”+ searchTerm +“] \ g”,“ig”); //匹配任何搜索字符的字符

然而,当我尝试使用正则表达式,像这样:

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

它似乎没有返回任何结果的话,即使我一个确切的名称类型。

任何帮助将是伟大的!

+0

这可能会帮助你http://stackoverflow.com/questions/9794851/find-text-string-in-jquery-and-make-it-bold/9795091#9795091 – elclanrs

回答

0

要匹配任何单词,尽量

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

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

更换

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

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

的区别是我们正在使用正则表达式比使用正则表达式对象。

+1

开始和结束字符以及全局标志在这里没有多大意义。 – elclanrs

+0

不知道是否包含它。固定。 – 2013-12-15 22:27:12

+0

@ aliasm2k我的OP中的代码在哪里?你可以使用代码示例吗? – StealthRT

0

这个fiddle的作品。

不知道原作者是用\\ g的东西来思考的。

的关键是这个表达式:

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

不确定你的小提琴的作品?如果你输入** ace **,它说它找不到它,即使* space *有* ace *。 – StealthRT

+0

也许我看着这个错误的方式..我正在寻找一种**通配符**,就像你会发现在SQL查询**%whateverHere%**。 – StealthRT

+0

啊,我误解了。该解决方案只能找到整个单词。给我一秒来匹配部分....看到http://jsfiddle.net/wmca4/5/ –