Skip to content

Instantly share code, notes, and snippets.

@tabula-rasa
Last active August 14, 2019 16:35
Show Gist options
  • Save tabula-rasa/718aaee7aa326966cb39bf6c5a18d552 to your computer and use it in GitHub Desktop.
Save tabula-rasa/718aaee7aa326966cb39bf6c5a18d552 to your computer and use it in GitHub Desktop.
JQuery filter on page with highlights
.hidden {
display: none!important;
}
mark {
background-color: #fcf8e3;
padding: 0.2em 0;
}
<!-- searh form ... -->
<input type="text" id="Query" class="form-control" onkeyup="onSearch();" placeholder="Search..." />
<!-- markup sample -->
<div class="exception">....</div>
<div class="exception">....</div>
<div class="exception">....</div>
<div class="exception">....</div>
<div class="exception">....</div>
<div class="exception">....</div>
<div class="exception">....</div>
$(document).ready(function () {
$.extend($.expr[":"], {
"containsCI": function (elem, i, match, array) {
return (elem.textContent || elem.innerText || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
}
});
$.extend($.expr[":"], {
"notContainsCI": function (elem, i, match, array) {
return (elem.textContent || elem.innerText || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) < 0;
}
});
function onSearch() {
var query = $('#Query').val();
$(".exception:notContainsCI('" + query + "')").addClass('hidden');
$(".exception:containsCI('" + query + "')").removeClass('hidden');
//++++++++++++
//clear all marks
$(".exception").not(".hidden").each(function () {
var html = this.innerHTML;
html = html.replace(new RegExp("(<mark>)([^<>]*)(<\\/mark>)", "gi"), "$2");
this.innerHTML = html;
});
//highlight text, 3 chars threshold
if (query.trim().length > 2) {
$(".exception").not('.hidden').each(function () {
var html = this.innerHTML;
//match only plain text, skip tag declarations, case insensitive, wrap exact matches with <mark> tag
//Regexp worth PhD in Computer Science
var re = new RegExp("(<[\\w]+[^>]*>)([^<>]*(" + query + ")[^<>]*)+(<\\/[\\w]+>)", "gi");
html = html.replace(re, function (match, submatch1, submatch2, submatch3, submatch4) {
//submatch2 is a full text inside the tag with possible multiple 'query' matches, replace them all
submatch2 = submatch2.replace(new RegExp("(" + query + ")", "gi"), "<mark>$1</mark>");
//omit submatch3
return submatch1 + submatch2 + submatch4;
});
this.innerHTML = html;
});
}
}
window.onSearch = onSearch;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment