Javascript search and display divs with matching keywords

后端 未结 2 887
南旧
南旧 2021-02-09 18:49

What I\'m looking for:

I\'m working on creating an easy way for a user to search a list of people, and for results to instantly display below the search field. The resul

2条回答
  •  日久生厌
    2021-02-09 19:24

    Split the words in the search string with a regex like

    searchString.split(/\W/);
    

    and do a OR search over each of the words in the resulting array.

    Updated fiddle

    var searchStrings = str_needle.split(/\W/);
    
    for (var i = 0, len = searchStrings.length; i < len; i++) {
        var currentSearch = searchStrings[i].toUpperCase();
        if (currentSearch !== "") {
            nameDivs = document.getElementsByClassName("name");
            for (var j = 0, divsLen = nameDivs.length; j < divsLen; j++) {
                if (nameDivs[j].textContent.toUpperCase().indexOf(currentSearch) !== -1) {
                    nameDivs[j].style.display = "block";
                }
            }
        }
    }
    

提交回复
热议问题