Remove case sensitivity in a JS search [duplicate] - javascript

This question already has answers here:
Contains case insensitive
(14 answers)
Closed 3 years ago.
I have a list on a page and a search bar that searches and filters the list as the user types. At the moment the input has to be all lowercase (which I've added myself). How can I remove all case sensitivity from the search string? For example if I search for teST the result for Test would still appear.
var list = $("table.ms-listviewtable");
var listItems = $("table.ms-listviewtable tr:not(.ms-viewheadertr)");
var input = $("input#filterInput");
input.keyup(function() {
listItems.each(function() {
var text = $(this).text();
var text = $(this).text().toLowerCase();
if (text.indexOf(input.val()) != -1) {
$(this).show();
} else {
$(this).hide();
}
});
});

Just use toLowerCase on input.val() as well as text.
if (text.indexOf(input.val().toLowerCase()) != -1) {...}
Also note you can use includes instead of indexOf on newer browsers:
if (text.includes(input.val().toLowerCase())) {...}

You can also use the .match method
var list = $("table.ms-listviewtable");
var listItems = $("table.ms-listviewtable tr:not(.ms-viewheadertr)");
var input = $("input#filterInput");
input.keyup(function() {
let inputVal = input.val().toLowerCase();
listItems.each(function() {
if($(this).text().toLowerCase().match(inputVal)){
$(this).show();
} else {
$(this).hide();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Related

jQuery if div contains multiple text strings

I had a quick script to search for some text (a unique code) in a div and hide a different element if it exists:
var itemCode = ["000001"];
if( $(".itemCode").text().indexOf(itemCode) >= 0) {
$(".codeBox").addClass("hideElement");
}
however I wanted to expand this so it finds one of multiple texts (codes) and if any of them exist then hide the element:
var itemCode = ["000001", "000003", "000008"];
if( $(".itemCode").text().indexOf(itemCode) >= 0) {
$(".codeBox").addClass("hideElement");
}
and this isn't working. I'm sure It's probably something simple and I'm supposed to add a .each() somewhere but I'm just not getting it working when I experiment trying things, what am I missing?
Might be slighty quicker if you have a few item codes in your array
var itemCode = ["000001", "000003", "000008"];
var regExpPattern = itemCode.join('|');
if($(".itemCode").text().match(new RegExp(regExpPattern, 'i'))) {
$(".codeBox").addClass("hideElement");
}
});
indexOf takes only one (mandatory) argument, so you'll have to iterate over your list to find element(s) matching your condition :
var itemCode = ["000001", "000003", "000008"];
var contains = itemCode.some(function(code) {
return $(".itemCode").text().indexOf(code) >= 0;
});
if (contains) {
$(".codeBox").addClass("hideElement");
}

Compare each element of one array to another and find which element is not found

I have two array which contains special characters am trying to compare each element of one array to another and get the element which is not found in another array. But my approach doesnt work properly
var specialChar = ['!','#','#','$','%','&'];
var $scope.inp= ['!','*','#'];
In my above example element '*' is not present specialChar
I tried this logic -
$scope.validateChar = function(specialChar,inp){
var i,j;
for (i=0,j=0; i<specialChar.length && j<inp.length;) {
if (specialChar[i] < inp[j]) {
++i;
} else if (specialChar[i] == inp[j]) {
++i; ++j;
} else {
$scope.notFoundChar = inp[j];
Error prompt showing special charatcter $scope.notFoundChar not found
$scope.charAllowedText = false;
return;
}
}
}
Please suggest what am doing wrong here?
You can filter out your Special char '*' like below
var result=[]
inp.map(function(inpElement){
if(specialChar.indexOf(inpElement)==-1)
result.push(inpElement)
})
console.log(result)
Below given code solves your problem.
var source = [1,2,3,4,5,6,7,8];
var target =[2,3,4,5,6,18,19];
var missingItems = [];
target.forEach(function(itemFromTarget){
var itemFound = false;
source.forEach(function(itemFromSrc){
if(itemFromTarget === itemFromSrc){
itemFound = true;
}
});
if (!itemFound) {
missingItems.push(itemFromTarget);
}
});
console.log(missingItems);

How to find if a value matches one of the values from an array in Javascript [duplicate]

This question already has answers here:
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 6 years ago.
FYI: this is for a simple quiz with just a single input field for each answer.
I have the following Javascript if statement to check if the value entered into an input field is correct (in this case, if the value entered is 'england').
$('input').keyup(function () {
if ($(this).val().toLowerCase() == 'england') {
//Stuff
} else {
//Other Stuff
};
});
However, I want to allow for alternative spellings, so I need a few possible answers for each question - it seems sensible to use an array for this as so...
var ans1 = new Array();
ans1[0] = "England";
ans1[1] = "Englund";
ans1[2] = "Ingland";
How can I change my if statement to say 'if the input field value equals any of those values from the array, then do the following'?
Any help would be greatly appreciated! Thank you.
You can do this using .inArray():
if ($.inArray($(this).val(), ans1) > -1) {
//Stuff
}
Here, the code $.inArray($(this).val(), ans1) will search for a specified value for example England within an array ans1 and return its index (or -1 if not found).
UPDATE
For case-sensitive search:
First enter all the values in the array in Lower Case
Next use the code below:-
JS:
if ($.inArray($(this).val().toLowerCase(), ans1) > -1) {
//Stuff
}
You can use the 'indexOf' method of the array, this will return -1 if the value doesn't exist in the array:
//if answer is in array
if(array.indexOf(answer) != -1){
//do stuff
}else{
//do stuff
}
Try this
if(this.value.match(/^(England|Englund|Ingland)$/i))
using regex and gi modifier for case insensitive
Do like this
$('input').keyup(function () {
var ans1 = new Array();
ans1[0] = "England";
ans1[1] = "Englund";
ans1[2] = "Ingland";
for(int i=0;i<ans1.length;i++)
{
if ($(this).val().toLowerCase() ==ans1[i]) {
//Stuff
} else {
//Other Stuff
};
}
});
Perhaps you may consider checking each element of the array like that:
var ans1 = new Array();
ans1[0] = "England";
ans1[1] = "Englund";
ans1[2] = "Ingland";
$('input').keyup(function () {
for (var i = 0; i < ans1.length; i++) {
if ($(this).val().toLowerCase() == ans1[i]) {
//Stuff
} else {
//Other Stuff
};
}
});
Not the most beautiful solution, but it should work.
jQuery offers $.inArray:
var found = $.inArray('specialword', words) > -1;
Note that inArray returns the index of the element found, so 0 indicates the element is the first in the array. -1 indicates the element was not found.
put your spellings in an array like this:
words: [
"England"
"Inglund"
"Ingland"
]
Found will be true if the word was found.
If you want the index of the matched word delete > -1 from the line.
Your code would be like this:
$('input').keyup(function () {
var found = $.inArray($(this).val(), words);
found > -1 ? //Stuff : //otherStuff;
});

Searching table rows with jQuery Non-Case sensitive [duplicate]

This question already has answers here:
Is there a case insensitive jQuery :contains selector?
(12 answers)
Closed 9 years ago.
I am trying out this nice little jQuery script for searching tables found here:
Searching table rows with jQuery
It works great, however I don't want it to be case sensitive, for example if a value in my table is Value One, I want to be able to search value one, or VALUE ONE and still get the right outcome.
This is the Jquery that controls it:
<script>
$(document).ready(function(){
$('input[name="search"]').keyup(function(){
var searchterm = $(this).val();
if(searchterm.length > 3) {
var match = $('tr.data-row:contains("' + searchterm + '")');
var nomatch = $('tr.data-row:not(:contains("' + searchterm + '"))');
match.addClass('selected');
nomatch.css("display", "none");
} else {
$('tr.data-row').css("display", "");
$('tr.data-row').removeClass('selected');
}
});
});
</script>
Can anyone help me with making it non case sensitive?
You can turn both strings into lowercase with the toLowerCase() method.
It should look something like this:
$(document).ready(function(){
$('input[name="search"]').keyup(function(){
var searchterm = $(this).val();
searchterm=searchterm.toLowerCase();
if(searchterm.length > 3) {
var match = $('tr.data-row:contains("' + searchterm + '")');
var nomatch = $('tr.data-row:not(:contains("' + searchterm + '"))');
match.addClass('selected');
nomatch.css("display", "none");
} else {
$('tr.data-row').css("display", "");
$('tr.data-row').removeClass('selected');
}
});
});
And you will need to override the jQuery method too! Something that looks like this...
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toLowerCase().indexOf(arg.toLowerCase()) >= 0;
};
});
It is pretty straight forward, all that you're doing is forcing both strings to be lower case before comparing them. That way you skip the different cases issue.
Hope this helps, good luck.
Your best best might be to write your own selector expression like this:
$.expr[":"].containsCI = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
You can find the solution here : Link , this will override the orginal ":contains" selector
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});

Jquery Search - Case insensitive

I have had some help on a Jquery script which creates a searchable, toggleable FAQ. The code can be seen here:
http://jsfiddle.net/pT6dB/62/
The trouble is, if there is the word “How” with an upper case “H” and I search “h”, it wont find it. How can I make this script case insensitive?
Update
Alternatively, you could reduce the amount of code significantly using regular expression. jsFiddle demo
$('#search').keyup(function(e) {
// create the regular expression
var regEx = new RegExp($.map($(this).val().trim().split(' '), function(v) {
return '(?=.*?' + v + ')';
}).join(''), 'i');
// select all list items, hide and filter by the regex then show
$('#result li').hide().filter(function() {
return regEx.exec($(this).text());
}).show();
});​
Original
Based on your current algorithm for determining relative elements, you could use the jQuery filter method to filter your results based on the keywords array. Here's a rough idea:
// select the keywords as an array of lower case strings
var keywords = $(this).val().trim().toLowerCase().split(' ');
// select all list items, hide and filter then show
$('#result li').hide().filter(function() {
// get the lower case text for the list element
var text = $(this).text().toLowerCase();
// determine if any keyword matches, return true on first success
for (var i = 0; i < keywords.length; i++) {
if (text.indexOf(keywords[i]) >= 0) {
return true;
}
}
}).show();
Change this line
$('#result LI:not(:contains('+keywords[i]+'))').hide();
to
$('#result LI').each(function()
{
if(this.innerHTML.toLowerCase().indexOf(keywords[i].toLowerCase()) === -1)
{
$(this).hide();
}
});
// split the search into words
var keywords = s.toLowerCase().split(' ');
// loop over the keywords and if it's not in a LI, hide it
for(var i=0; i<keywords.length; i++) {
$('#result LI').each(function (index, element) {
if ($(element).text().toLowerCase().indexOf(keywords) != -1) {
$(element).show();
} else {
$(element).hide();
}
});
}

Categories

Resources