javascript includes() case insensitive
You can create a RegExp from filterstrings
first
var filterstrings = ['firststring','secondstring','thridstring'];
var regex = new RegExp( filterstrings.join( "|" ), "i");
then test
if the passedinstring
is there
var isAvailable = regex.test( passedinstring );
Case-insensitive Array#include?
Summary
If you are only going to test a single word against an array, or if the contents of your array changes frequently, the fastest answer is Aaron's:
array.any?{ |s| s.casecmp(mystr)==0 }
If you are going to test many words against a static array, it's far better to use a variation of farnoy's answer: create a copy of your array that has all-lowercase versions of your words, and use include?
. (This assumes that you can spare the memory to create a mutated copy of your array.)
# Do this once, or each time the array changes
downcased = array.map(&:downcase)
# Test lowercase words against that array
downcased.include?( mystr.downcase )
Even better, create a Set
from your array.
# Do this once, or each time the array changes
downcased = Set.new array.map(&:downcase)
# Test lowercase words against that array
downcased.include?( mystr.downcase )
My original answer below is a very poor performer and generally not appropriate.
Benchmarks
Following are benchmarks for looking for 1,000 words with random casing in an array of slightly over 100,000 words, where 500 of the words will be found and 500 will not.
- The 'regex' text is my answer here, using
any?
. - The 'casecmp' test is Arron's answer, using
any?
from my comment. - The 'downarray' test is farnoy's answer, re-creating a new downcased array for each of the 1,000 tests.
- The 'downonce' test is farnoy's answer, but pre-creating the lookup array once only.
- The 'set_once' test is creating a
Set
from the array of downcased strings, once before testing.
user system total real
regex 18.710000 0.020000 18.730000 ( 18.725266)
casecmp 5.160000 0.000000 5.160000 ( 5.155496)
downarray 16.760000 0.030000 16.790000 ( 16.809063)
downonce 0.650000 0.000000 0.650000 ( 0.643165)
set_once 0.040000 0.000000 0.040000 ( 0.038955)
If you can create a single downcased copy of your array once to perform many lookups against, farnoy's answer is the best (assuming you must use an array). If you can create a Set
, though, do that.
If you like, examine the benchmarking code.
Original Answer
I (originally said that I) would personally create a case-insensitive regex (for a string literal) and use that:
re = /\A#{Regexp.escape(str)}\z/i # Match exactly this string, no substrings
all = array.grep(re) # Find all matching strings…
any = array.any?{ |s| s =~ re } # …or see if any matching string is present
Using any?
can be slightly faster than grep
as it can exit the loop as soon as it finds a single match.
PHP case-insensitive in_array function
you can use preg_grep()
:
$a= array(
'one',
'two',
'three',
'four'
);
print_r( preg_grep( "/ONe/i" , $a ) );
Why is includes in JavaScript case sensitive?
Why would it work case-insensitively? Quoth the MDN:
The
includes()
method determines whether an array includes a certain value among its entries, returning true or false as appropriate.
[...]
Note: Technically speaking, includes() uses thesameValueZero
algorithm to determine whether the given element is found.
sameValueZero
is defined to be Object.is
but with +0
and -0
being equal.
That being the case, we can try that out:
> Object.is("bmw", "BMW")
false
> Object.is("bmw", "bmw")
true
Javascript - Case insensitive Array Search
You don't need jQuery.
Use the function
findIndex
and convert to lowerCase every element for each comparison.
var x = ["AAA", "aaa", "bbb", "BBB"];
function unique(list) {
var result = [];
list.forEach(function(e) {
if (result.findIndex(function(r) {
return r.toLowerCase() === e.toLowerCase();
}) === -1)
result.push(e);
});
return result;
}
console.log(unique(x))
.as-console-wrapper { max-height: 100% !important; top: 0; }
How do I make Array.indexOf() case insensitive?
Easy way would be to have a temporary array that contains all the names in uppercase. Then you can compare the user input. So your code could become somthing like this:
function delName() {
var dnameVal = document.getElementById('delname').value;
var upperCaseNames = names.map(function(value) {
return value.toUpperCase();
});
var pos = upperCaseNames.indexOf(dnameVal.toUpperCase());
if(pos === -1) {
alert("Not a valid name");
}
else {
names.splice(pos, 1);
document.getElementById('canidates').innerHTML =
"<strong>List of Canidates:</strong> " + names.join(" | ");
}
}
Hope this helps solve your problem.
How can I make Array.Contains case-insensitive on a string array?
array.Contains("str", StringComparer.OrdinalIgnoreCase);
Or depending on the specific circumstance, you might prefer:
array.Contains("str", StringComparer.CurrentCultureIgnoreCase);
array.Contains("str", StringComparer.InvariantCultureIgnoreCase);
is possible to do case-insensitive search through _.includes?
You could use some instead:
_.some(["Name1","Name2"], function(el) { return el.toLowerCase() === 'name1'; });
var result = _.some(["Name1","Name2"], function(el) {
return el.toLowerCase() === 'name1';
});
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
Related Topics
How to Add a New Action to the Existing Controller
How to See the Dependency Tree Just from Gemfile
Ruby - Replace the First Occurrence of a Substring with Another String
Writing Over Previously Output Lines in the Command Prompt with Ruby
Empty Attribute with Ruby Haml
Heroku Wrongly Detecting My Node App as a Ruby App
Suppressing the Output of a Command Run Using 'System' Method While Running It in a Ruby Script
Ruby 2.0 How to Uninclude a Module Out from a Module After Including It
How to Create a Full Audit Log in Rails for Every Table
How to Get the Target of a Symlink
Rails 6.1, Ruby 3.0.0: Tests Error as They Cannot Load Rexml
Run Ruby Script in Elevated Mode
How to Wrap the Invocation of a Ruby Method by Including a Module