Declaration:
let listArray = ["kashif"] let word = "kashif"
then this
contains(listArray, word)
Returns true but if declaration is:
let word = "Kashif"
then it returns false because comparison is case sensitive.
How to make this comparison case insensitive?
You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.
Both String#includes() and String#indexOf() are case sensitive. Neither function supports regular expressions. To do case insensitive search, you can use regular expressions and the String#match() function, or you can convert both the string and substring to lower case using the String#toLowerCase() function.
The indexof() method in Javascript is one of the most convenient ways to find out whether a value exists in an array or not. The indexof() method works on the phenomenon of index numbers. This method returns the index of the array if found and returns -1 otherwise.
includes() method case insensitive, convert both of the strings in the comparison to lowercase, e.g. str. toLowerCase(). includes(substr. toLowerCase()) .
Xcode 8 • Swift 3 or later
let list = ["kashif"] let word = "Kashif" if list.contains(where: {$0.caseInsensitiveCompare(word) == .orderedSame}) { print(true) // true }
alternatively:
if list.contains(where: {$0.compare(word, options: .caseInsensitive) == .orderedSame}) { print(true) // true }
if you would like to know the position(s) of the element in the array (it might find more than one element that matches the predicate):
let indices = list.indices.filter { list[$0].caseInsensitiveCompare(word) == .orderedSame } print(indices) // [0]
You can also use localizedStandardContains method which is case and diacritic insensitive and would match a substring as well:
func localizedStandardContains<T>(_ string: T) -> Bool where T : StringProtocol
Discussion This is the most appropriate method for doing user-level string searches, similar to how searches are done generally in the system. The search is locale-aware, case and diacritic insensitive. The exact list of search options applied may change over time.
let list = ["kashif"] let word = "Káshif" if list.contains(where: {$0.localizedStandardContains(word) }) { print(true) // true }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With