Search with case insensitive

Asked

Viewed 260 times

3

Good afternoon, I have a search field but I need it to return the values regardless of toLowerCase() and toUpperCase()

Ex Bola, I can look up how ball or else BALL

I have the following line of code:

function filterMaterialList(query){
    let categorySelect = document.querySelector('select[name=category]');
    let materialList = materials[categorySelect.value];
    let reducedList = [];

    if(query === ''){
        return materialList;
    }

    for(let material of materialList){
        if(material.name.toLowerCase().indexOf(query) != -1){
            reducedList.push(material);
        }
    }

    if(reducedList.length == 0){
        reducedList.push({name: 'Nenhum resultado encontrado!', id: null});
    }

    return reducedList;
}

but how I’m using:

if(material.name.toLowerCase().indexOf(query) != -1){... I only succeed when I search for ball

I need this function to be case insensitive, someone can help me ?

2 answers

7

being the parameter "query" its search criteria, follows suggestion: just put the query.toLowerCase(), thus, regardless of the way the search criteria is informed, both will be compared with Lower-Case.

function filterMaterialList(query){
    let categorySelect = document.querySelector('select[name=category]');
    let materialList = materials[categorySelect.value];
    let reducedList = [];

    if(query === ''){
        return materialList;
    }

    for(let material of materialList){
        if(material.name.toLowerCase().indexOf(query.toLowerCase()) != -1){
            reducedList.push(material);
        }
    }

    if(reducedList.length == 0){
        reducedList.push({name: 'Nenhum resultado encontrado!', id: null});
    }

    return reducedList;
}

6


The simplest/practical way is to also string query for the same format:

if (material.name.toLowerCase().indexOf(query.toLowerCase()) != -1)
  • maaaaano Thank you very much vei, was banging head here, saved big kkkkkkk, already put as correct answer

  • :D mass that solved

Browser other questions tagged

You are not signed in. Login or sign up in order to post.