Search with case insensitive

3

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

Ex Ball, I can search as ball or 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;
}

however as 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, can anyone help me?

    
asked by anonymous 23.10.2018 / 19:17

2 answers

6

The simplest / most practical way is to pass the query string to the same format:

if (material.name.toLowerCase().indexOf(query.toLowerCase()) != -1)
    
23.10.2018 / 19:22
7

The parameter "query" is your search criterion, it follows suggestion: just put query.toLowerCase() , that way, regardless of the form that 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;
}
    
23.10.2018 / 19:24