JS - jQuery inarray ignoreCase () and contains ()

Well, I'm more of a PHP person, and my JS skills are close to anyone when it comes to any JS other than simple design-related operations, so excuse me if I ask the obvious.

the following operations would be easy in PHP (and may also be in JS), but I'm fighting the unfamiliar syntax here ...)

This is a kind of input confirmation

var ar = ["BRS201103-0783-CT-S", "MAGIC WORD", "magic", "Words", "Magic-Word"]; jQuery(document).ready(function() { jQuery("form#searchreport").submit(function() { if (jQuery.inArray(jQuery("input:first").val(), ar) != -1){ jQuery("#contentresults").delay(800).show("slow"); return false; } 

This question has two parts.

  • 1 - how can I let an array be case insensitive?

eg. - BRS201103-0783-CT-S will give the same result as BRS201103-0783-CT-S AND BRS201103-0783-CT-S or MAGIC magic Magic MaGIc

Basically, I need something like ignoreCase () for the array, but I could not find a link to jQuery and JS ...

I tried toLowerCase() - but it does not work on the array (ittirating?), And also, will it allow a mixed case?

  • 2 - How can I make a function recognize only parts or combinations of elements?

eg. - if one type is only "word" , I would like it to go like "words" , and also, if someone types "some word" , it should pass (containing the word)

+7
source share
2 answers

Part 1

You can process your array so that it is completely lowercase and type in the string input, so indexOf() will work as if it is case-insensitive.

You can enter a string with toLowerCase() string, as you already understood.

To make an array, you can use ...

 arr = arr.map(function(elem) { return elem.toLowerCase(); }); 

Part 2

You can check for a substring, for example ...

 // Assuming you've already transformed the input and array to lowercase. var input = "word"; var words = ["word", "words", "wordly", "not"]; var found = words.some(function(elem) { return elem.indexOf(input) != -1; }); 

Alternatively, you can skip the conversion of an array to any register in this example by calling toLowerCase() on each elem before you check indexOf() .

some() and map() not supported in old IEs, but are trivial for polyfill. An example polyfill for each of them is available in the related documentation.

As Fabrício Matté also pointed out, you can use jQuery equivalents, $.map() for Array.prototype.map() and $.grep() with the length property for Array.prototype.some() . You will then receive free browser support.

+8
source

To check if the array contains a case insensitive element, I used this code:

  ret = $.grep( array, function (n,i) { return ( n && n.toLowerCase().indexOf(elem.toLowerCase())!=-1 ); }) ; 

Here is a fiddle to play with an array is not case sensitive

+1
source

All Articles