我在搜索文本时遇到了一个问题。我认为这是正则表达式/替换问题的问题。
我的搜索功能运行良好,但问题是当我搜索大写字母“N”时,所有小写字母“n”都会变为大写字母。
这是我使用的...尝试搜索“N”,您会看到所有小的“n”都变为大写“N”。
http://jsfiddle.net/ravi1989/4BAau/3/
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 || "#realTimeContents"; //use body as selector if none provided
var searchTermRegEx = new RegExp(searchTerm, "ig");
var matches = $(selector).text().match(searchTermRegEx);
if (matches != null && matches.length > 0) {
$('.highlighted').removeClass('highlighted'); //Remove old search highlights
//Remove the previous matches
$span = $('#realTimeContents span');
$span.replaceWith($span.html());
var content = "<span class='match'>" + searchTerm + "</span>";
var replaced = $(selector).text().replace(searchTermRegEx, content);
$(selector).html(replaced);;
$('.match:first').addClass('highlighted');
var i = 0;
$('.next_h').off('click').on('click', function () {
i++;
if (i >= $('.match').length) i = 0;
$('.match').removeClass('highlighted');
$('.match').eq(i).addClass('highlighted');
$('.ui-mobile-viewport').animate({
scrollTop: $('.match').eq(i).offset().top
}, 300);
});
$('.previous_h').off('click').on('click', function () {
i--;
if (i < 0) i = $('.match').length - 1;
$('.match').removeClass('highlighted');
$('.match').eq(i).addClass('highlighted');
$('.ui-mobile-viewport').animate({
scrollTop: $('.match').eq(i).offset().top
}, 300);
});
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).on('click', '.searchButtonClickText_h', function (event) {
$(".highlighted").removeClass("highlighted").removeClass("match");
if (!searchAndHighlight($('.textSearchvalue_h').val())) {
alert("No results found");
}
});