嘿,我发现以下代码在页面中找到了一个单词:
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");
即使我输入确切的名称,它似乎也不会返回任何结果。
任何帮助都会很棒!
答案 0 :(得分:1)
此fiddle有效。
不确定原作者用\\ g的东西在想什么。
关键是这个正则表达式:
searchRegex = new RegExp('(\\b)(' + searchTerm + ')(\\b)','ig');
答案 1 :(得分:0)
要匹配任何字词,请尝试
/^\b\w+\b$/i
正则表达式匹配单词边界之间的多个字符
替换
var searchTermRegEx = new RegExp("\\g["+searchTerm+"]\\g","ig");
与
var searchTermRegEx = /^\b\w+\b$/i;
不同之处在于我们使用正则表达式文字比使用正则表达式对象。