JS - jQuery inarray ignoreCase() and contains()

帅比萌擦擦* 提交于 2019-12-01 16:56:35
alex

Part 1

You can process your array to be entirely lowercase, and lowercase your input so indexOf() will work like it's performing a case insensitive search.

You can lowercase a string with toLowerCase() as you've already figured out.

To do an array, you can use...

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

Part 2

You could 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 could skip in this instance transforming the array to be all lowercase by calling toLowerCase() on each elem before you check indexOf().

some() and map() aren't supported in older IEs, but are trivial to polyfill. An example of a polyfill for each is available at the linked documentation.

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

To check if an array contains an element, case-insensitive, 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 array match case insensitive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!