Search code examples
javascriptarrayscase-insensitive

how can i make the input value case-insenstive in an array using pure javascript


I want to be able to search for a value without having to explicitly type in the first letter using uppercase. Hence it can be recognised in lowerCase also. Any help please?

function animal(){
        var animal = ["Panda", "Snake", "Lemur", "Tortoise", "Whale", "Cat", "Elephant", "Jaguar", "Panther", "Llama", "Horse", "Cheetah", "Leopard", "Anteater", "Tazmanian Devil"];

            if(animal.includes(document.getElementById("animalName").value)){
                console.log("That animal is available");
            }
            else{
                console.log("That animal is not available at the moment");
            }

        }

Solution

  • Simply test lowercase values. Also, I would suggest to cache the input DOM element and to define the array outside of the function, so they're not uselessly redefined every time the function is called.

    const animalName = document.getElementById("animalName"),
           animal = ["panda", "snake", "lemur", "tortoise", "whale", "cat", "elephant", "jaguar", "panther", "llama", "horse", "cheetah", "leopard", "anteater", "tazmanian devil"]
    
    function animal(){
            let typed = animalName.value.toLowerCase().trim()
    
            if(animal.includes(typed)){
              console.log("That animal is available");
            } else {
              console.log("That animal is not available at the moment");
            }
    }