I got this search table with multiple words and display multiple results. But I have a problem in search exact word like "Male" and "Female" when I search "Male" the female is also displayed because the female has "male" word. How will I find the exact word?
if (!RegExp.escape) {
RegExp.escape = function (s) {
return s.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&")
};
}
jQuery(function ($) {
///search this table
$(' #search ').click(function () {
var searchthis = new RegExp($(' #emp_search ').val().replace(/ /g,"|"), 'i');
alert(searchthis);
$("table").find("tr").slice(1).each(function (index) {
// var text = $(this).find("td").text().toLowerCase().trim();
var text = $.trim($(this).text());
$(this).toggle(searchthis.test(text));
});
});
});
http://jsfiddle.net/wind_chime18/ANLgD/11/
just added a space:
var searchthis = new RegExp(' '+$(' #emp_search ').val().replace(/ /g,"|"), 'i');
and updated your fiddle:http://jsfiddle.net/ANLgD/12/
http://jsfiddle.net/ANLgD/17/
$(function () {
$(' #search ').click(function () {
var str = $('#emp_search').val();
var strary = str.split(' ');
$("table").find("tr").slice(1).each(function (index) {
var text = $.trim($(this).text());
for (var i = 0; i < strary.length; i++) {
var regex = new RegExp(".*\\b" + strary[i] + "\\b\.*", "gi");
$(this).toggle(regex.test(text));
if (regex.test(text)) break;
}
});
});
});
Related
I'm currently building a page where a search field acts as a filter. It works perfectly fine and shows data against related word, but there is one issue that I'd like to solve. When the entered string or other words is not found in all the existing the page remains blank.
How could I display a default message on my page when no results are found by the filter? Something like a simple <p> explaining that no results were found.
The idea is to display it only once as long as the string is not found.
$('#search_field').on('keyup', function() {
var value = $(this).val();
var patt = new RegExp(value, "i");
$('#userFind').find('tr').each(function() {
var $table = $(this);
if (!($table.find('td').text().search(patt) >= 0)) {
$table.not('.t_head').hide();
}
if (($table.find('td').text().search(patt) >= 0)) {
$(this).show();
}
});
});
This is untested since you haven't provided any table to your question.
After you have looped though all tr, then check if any is visible. If not then append a tr with custom message and remove it and new search.
$('#search_field').on('keyup', function() {
var value = $(this).val();
// console.log(value);
var patt = new RegExp(value, "i");
$(".noRecord").remove();
$('#userFind').find('tr').each(function() {
var $table = $(this);
if (!($table.find('td').text().search(patt) >= 0)) {
$table.not('.t_head').hide();
} else {
$(this).show();
}
});
if ($('#userFind tr:visible').length == 0) {
$('#userFind tbody').append("<tr class='noRecord'><td>No records found.</td></tr>")
}
});
Assuming you have a div:
<div id="zeroHits">no results were found</div>
You can hide/show the #zeroHits div as follows:
$('#search_field').on('keyup', function() {
var value = $(this).val();
var patt = new RegExp(value, "i");
var zeroHits = true;
$('#userFind').find('tr').each(function() {
var $table = $(this);
if (!($table.find('td').text().search(patt) >= 0)) {
$table.not('.t_head').hide();
}
if (($table.find('td').text().search(patt) >= 0)) {
$(this).show();
zeroHits = false;
}
});
if(zeroHits) {
$('#zeroHits').show();
} else {
$('#zeroHits').hide();
}
});
Try this untested code
post your HTML and I can test
const $rows = $('#userFind tbody tr'); // only tbody rows
$('#search_field').on('keyup', function() {
var value = $(this).val();
// console.log(value);
var patt = new RegExp(value, "i");
$rows.each(function() {
const found = $(this).find('td').filter(function() {
return $(this).text().search(patt) != -1
}).length > 0
$(this).toggle(found);
});
$("#notFound").toggle($rows.filter(":visible").length === 0)
});
I have some problem with my code. On search i'm trying to find letter or a word and highlight it but have some problem for example when I search on word 'Aram' it return me 'ArAm'. When in a word I have more same letter and first one is capital all other letters replaced with capital letters. Can You please check my code and say what i do wrong.
example 'Aram' -> 'ArAm(<mark>A</mark>r<mark>A</mark>m)' but shuld be 'Aram(<mark>A</mark>r<mark>a</mark>m)'
JavaScript:
$("input").on("keyup", function () {
var valThis = this.value;
$('table').find('tr td').each(function () {
if($(this).attr('data-search') !== 'false') {
console.log('');
var text = $(this).text();
var textL = text.toLowerCase();
var position = textL.indexOf(valThis.toLowerCase());
if (position !== -1) {
var matches = text.substring(position, ( valThis.length + position ));
var regex = new RegExp(matches, 'ig');
var highlighted = text.replace(regex, `<mark>${matches}</mark>`);
console.log(highlighted);
$(this).html(highlighted);
setTimeout(function () {
if($(this).parent().find('mark').is(':empty')) {
$('mark').remove();
}
}.bind(this),0);
} else {
console.log('sadasdasd');
$(this).text(text);
}
}
if($(this).parent().find('mark').length > 0) {
$(this).parent().show();
}else {
$(this).parent().hide();
}
});
});
Here is my jsFiddle
Thanks for your help
Try this:
var regex = new RegExp(valThis, 'ig');
text = text.replace(regex, (match, $1) => {
// Return the replacement
return '<mark>' + match + '</mark>';
});
$(this).html(text);
JSFiddle
As an example, if I have 'vegetables' in my list and I type a letter 'e', all three letter 'e's in 'vegetables' should become bold. I have played around with the code at the fiddles I found on the web below, but with them, I can only get the beginning of the words bold or the middle of words.
https://jsfiddle.net/ku5zv3dz/
var inputId = 'mytextbox';
var itemsData = 'value';
var displaySet = false;
var displayArr = [];
function getDisplayType(element) {
var elementStyle = element.currentStyle || window.getComputedStyle(element, "");
return elementStyle.display;
}
document.getElementById(inputId).onkeyup = function() {
var currval = this.value;
var searchVal = this.value.toLowerCase();
var filterItems = document.querySelectorAll('[' + itemsData + ']');
for(var i = 0; i < filterItems.length; i++) {
if (!displaySet) {
displayArr.push(getDisplayType(filterItems[i]));
}
var textcontent = filterItems[i].textContent;
var replacedval = "<strong>"+currval+"</strong>"
var finalval = textcontent.replace(currval, replacedval);
filterItems[i].innerHTML = finalval;
filterItems[i].style.display = 'none';
if(filterItems[i].getAttribute('value').toUpperCase().indexOf(searchVal.toUpperCase()) >= 0) {
filterItems[i].style.display = displayArr[i];
}
}
displaySet = true;
}
http://jsfiddle.net/noth1ng/ytYQd/
$('#mytextbox').keyup(function () {
var valThis = this.value.toLowerCase(),
length = this.value.length;
$('#mydropdown>option').each(function () {
var text = $(this).text(),
textL = text.toLowerCase(),
htmlR = '<b>' + text.substr(0, length) + '</b>' + text.substr(length);
(textL.indexOf(valThis) == 0) ? $(this).html(htmlR).show() : $(this).hide();
});
});
This is the original code before trying to add the feature for bold:
jQuery.fn.filterByText = function(mytextbox) {
return this.each(function() {
var select = this;
var options = [];
$(mydropdown).find('option').each(function() {
options.push({
value: $(this).val(),
text: $(this).text()
});
});
$(mydropdown).data('options', options);
$(mytextbox).bind('change keyup', function() {
var options = $(mydropdown).empty().data('options');
var search = $.trim($(this).val().replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"));
var regex = new RegExp(search, "gi");
$.each(options, function(i) {
var option = options[i];
if (option.text.match(regex) !== null) {
$(mydropdown).append(
$('<option>').text(option.text).val(option.value)
);
}
});
});
});
};
I used the valThis to create the RegExp and use the replace method to replace all occurrences with the bold value.
$('#box').keyup(function () {
var valThis = this.value.toLowerCase(),
lenght = this.value.length;
$('.navList>li').each(function () {
var text = $(this).text(),
textL = text.toLowerCase();
var replace = "(" + valThis + ")";
var re = new RegExp(replace,"g");
textL = textL.replace(re,"<b>" + valThis + "</b>");
$(this).html(textL);
});
});
http://jsfiddle.net/54rya8p4/
I need to do as follows:
I've got an array of strings containing last names. Some of them ends with letter 'i'.
manLastNames = ["testowski","bucz","idzikowski","gosz"];
I need to make a function which will iterate over this array of strings and if there is an element ending with 'i', I need to replace this 'i' for 'a', otherwise just leave string as it is.
At the end I want to have another array where all last 'i's are replaced with 'a's.
womanLastNames = ["testowska","bucz","idzikowska","gosz"];
This is what I have now, but Im pretty sure that it start being crap at some point
var rep = function() {
var manLastNames = ["testowski","bucz","idzkowski","gosz"];
var womanLastNames = new Array(4);
for (var i=0; i<manLastNames.length; i++) {
var lastName = manLastNames[i];
if (lastName.substr(lastName.length - 1, 1) == 'i') {
lastName = lastName.substr(0, lastName.length - 1) + 'a';
}
}
for (var i=0; i<womanLastNames.length; i++) {
womanLastNames[i] = lastName[i];
}
console.log(womanLastNames);
}
rep();
Try the code:
var manNames = ["testowski","bucz","idzkowski","gosz"];
var womanNames = manNames.map(function(name) {
return name.endsWith("i") ? name.slice(0, -1) + "a" : name;
});
console.log(womanNames)
If your interpreter supports ES6, the following is equivalent:
names.map((name)=>name.endsWith("i") ? name.slice(0, -1) + "a" : name)
Here is solution
var rep = function() {
var manLastNames = ["testowski","bucz","idzkowski","gosz"];
var womanLastNames =[];
for (var i=0; i<manLastNames.length; i++) {
var lastName = manLastNames[i];
if (lastName.charAt(lastName.length - 1) == 'i') {
lastName = lastName.substr(0, lastName.length - 1) + 'a';
}
womanLastNames.push(lastName);
}
console.log(womanLastNames);
}
rep();
Another solution is to use .map method like this, using a callback function:
var manLastNames = ["testowski","bucz","idzikowski","gosz"];
function mapNames(item){
return item[item.length-1]=='i' ? item.substr(0, item.length-1) + "a" : item;
}
console.log(manLastNames.map(mapNames));
Depending on how efficient you need to be, you can use regular expressions to do both tasks:
var new_name = name.replace(/i$/, 'a');
will replace the last "i" in a string with "a" if it exists
var new_name = name.replace(/i/g, 'a');
will replace all "i"s in a string with "a".
var names = ["testowski", "bucz", "idzkowski", "gosz"];
console.log("original", names);
var last_i_replaced = names.map(function(name) {
return name.replace(/i$/, 'a');
});
console.log("last 'i' replaced", last_i_replaced);
var all_i_replaced = names.map(function(name) {
return name.replace(/i/g, 'a');
});
console.log("all 'i's replaced", all_i_replaced);
This should work:
var rep = function() {
var manLastNames = ["testowski","bucz","idzkowski","gosz"];
var womanLastNames = manLastNames;
for(var i=0; i<manLastNames.length;i++){
if(manLastNames[i].charAt(manLastNames[i].length-1)=='i'){
womanLastNames[i]=manLastNames[i].substr(0,womanLastNames[i].length-1)+'a';
}
}
console.log(womanLastNames);
}
rep();
Here is another solution
var manLastNames = ["testowski","bucz","idzkowski","gosz"];
var womanLastNames = []
manLastNames.forEach(x => {
if (x.charAt(x.length-1) === "i") womanLastNames.push(x.slice(0,-1).concat("a"));
else womanLastNames.push(x);
});
console.log(womanLastNames);
I am working on search in a text .Actually I am searching a text from Text .But I am facing a problem in case sensitive .If you search for "n" it work fine .But when you search for "N", it convert the all "n" to capital "N"and then search .I don't know why it is occurring in searching..?.
here is my try..
http://jsfiddle.net/wjLmx/23/
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());
if (searchTerm === "&") {
searchTerm = "&";
searchTermRegEx = new RegExp(searchTerm, "ig");
}
$(selector).html($(selector).html().replace(searchTermRegEx, "<span class='match'>" + searchTerm + "</span>"));
$('.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");
}
});
Your problem is the following line:
$(selector).html($(selector).html().replace(searchTermRegEx, "<span class='match'>" + searchTerm + "</span>"));
which replace the matches with the searchTerm (e.g. "N").
Try replacing it to something like the following to replace it with what was matched:
$(selector).html($(selector).html().replace(searchTermRegEx, "<span class='match'>" + matches[0] + "</span>"));
If you want to stop the search being case insensitive, drop the i from your regex.
var searchTermRegEx = new RegExp(searchTerm, "g");