Any way to make jQuery.inArray() case insensitive?

后端 未结 8 1589
轮回少年
轮回少年 2020-12-03 16:44

Title sums it up.

相关标签:
8条回答
  • 2020-12-03 17:07

    You can use each()...

    // Iterate over an array of strings, select the first elements that 
    // equalsIgnoreCase the 'matchString' value
    var matchString = "MATCHME".toLowerCase();
    var rslt = null;
    $.each(['foo', 'bar', 'matchme'], function(index, value) { 
      if (rslt == null && value.toLowerCase() === matchString) {
        rslt = index;
        return false;
      }
    });
    
    0 讨论(0)
  • 2020-12-03 17:10

    Thank you to @Drew Wills.

    I rewrote it as this:

    function inArrayCaseInsensitive(needle, haystackArray){
        //Iterates over an array of items to return the index of the first item that matches the provided val ('needle') in a case-insensitive way.  Returns -1 if no match found.
        var defaultResult = -1;
        var result = defaultResult;
        $.each(haystackArray, function(index, value) { 
            if (result == defaultResult && value.toLowerCase() == needle.toLowerCase()) {
                result = index;
            }
        });
        return result;
    }
    
    0 讨论(0)
  • 2020-12-03 17:13

    No. You will have to fiddle with your data, I usually make all my strings lowercase for easy comparisons. There is also the possibility of using a custom comparison function which would do the necessary transforms to make the comparison case insensitive.

    0 讨论(0)
  • 2020-12-03 17:13

    These days I prefer to use underscore for tasks like this:

    a = ["Foo","Foo","Bar","Foo"];
    
    var caseInsensitiveStringInArray = function(arr, val) {
        return _.contains(_.map(arr,function(v){
            return v.toLowerCase();
        }) , val.toLowerCase());
    }
    
    caseInsensitiveStringInArray(a, "BAR"); // true
    
    0 讨论(0)
  • 2020-12-03 17:15

    This way worked for me..

    var sColumnName = "Some case sensitive Text"
    
    if ($.inArray(sColumnName.toUpperCase(), getFixedDeTasksColumns().map((e) => 
    e.toUpperCase())) == -1) {// do something}
    
    0 讨论(0)
  • 2020-12-03 17:27

    could loop through the array and toLower each element and toLower what you're looking for, but at that point in time, you may as well just compare it instead of using inArray()

    0 讨论(0)
提交回复
热议问题