I took this code from a blog which I don't remember the URL. The code is supposed to find in a list with many sections the text written by the user in an input field. If there is a match, the text will be highlighted; and if there is no match, the whole section will hide.
I've made a plunker so you can see how it works: Here's the link
This is the JS code:
$(document).ready(function() {
var $container = $('#global_div');
if (!$container.length) return true;
var $input = $('#searcher'),
$notfound = $('.not-found'),
$items = $container.find('.row'),
$item = $(),
itemsIndexed = [];
$items.each(function() {
itemsIndexed.push($(this).text().replace(/\s{2,}/g, ' ').toLowerCase());
});
$input.on('keyup', function(e) {
$items.each(function() {
$item = $(this);
$item.html($item.html().replace(/<span class="highlight">([^<]+)<\/span>/gi, '$1'));
});
var searchVal = $.trim($input.val()).toLowerCase();
if (searchVal.length) {
for (var i in itemsIndexed) {
$item = $items.eq(i);
if (itemsIndexed[i].indexOf(searchVal) != -1)
$item.removeClass('is-hidden').html($item.html().replace(new RegExp(searchVal + '(?!([^<]+)?>)', 'gi'), '<span class="highlight">$&</span>'));
else
$item.addClass('is-hidden');
}
} else $items.removeClass('is-hidden');
$notfound.toggleClass('is-visible', $items.not('.is-hidden').length == 0);
});
});
So far so good, but the problem is when there are certain characters in the html text or when writing some special characters in the input field. Please open the plunker so you can do the tests I'm about to tell you:
When writing down the letters "a", "s" or "n", you can see how it shows the & ;
and   ;
of the html. Also when writing down "&", and the whole thing breaks when writing a "." (point).
As I couldn't fix this, I added this code to avoid people from writing special characters in the input (this code isn't in the plunker, so you can test the errors):
$("#searcher").keypress(function(event) {
var character = String.fromCharCode(event.keyCode);
return isValid(character);
});
function isValid(str) {
return !/[~`!@#$%\^&*()+=\-\[\]\\';/{}|\\":.<>\?]/g.test(str);
}
But there is still the problem when there are characters like & ;
and   ;
in the html and users write in the input field the letter "a", "s" or "n" ..or depending which other weird character be on the html.