简体   繁体   中英

Don't take whitespace in my array [Javascript]

it's my first post then sorry for that. I try to explain you the concept and the objectif

I have this code for a FAQ. The objectif is to search your problem with few words in a search bar (with an input). You write 1 or 2 words with a "whitespace" and all topic who match with the words, they display them and others they display:none.

My question is : Before to display them, I try to push the results good in a array[]. But the problem is with my input, he takes the whitespace and he returns all results. Then I trying to split(), to regexp my input, in Javascript , for delete this whitespace and to returns only the words who the client write but Im a newbie.

Im here if you got more questions. Thx

filterSearchFaq = inputSearchFaq.value.toUpperCase();
splitInput = filterSearchFaq.split(/\s+/);
ulSearchFaq = document.getElementById("listQuestionResponseFaq");
liSearchFaq = ulSearchFaq.getElementsByTagName("li");
var countFound = 0;
var array = [];

    for (var i = 0; i < splitInput.length; i++) {                   
        var word = splitInput[i];                   
            for (var j = 0; j < liSearchFaq.length; j++) {
               var panelClass = 
               liSearchFaq[j].getElementsByClassName("panel");
                  if (null != panelClass[0]) {
                      panel = liSearchFaq[j].getElementsByClassName("panel")[0];
                      searchIndex =  panel.innerHTML.toUpperCase().indexOf(word);
                        if (searchIndex > -1) {
                                array.push(searchIndex);
                            }                                                           
                        }        
                    }

            }

console.log

You can see the second word, its a whitespace because I press my space bar, but I want to delete this whitespace when the client will press the spacebar

[from comments] if I don't put any words in my input or I put a space after my first or second world, I got a : " " in my array and it returns all my answers. My questionn is How can i delete this white space in my array.

One easy way around that would be to switch from splitting to matching:

" foo bar baz ".match(/(\S+)/g)

this will capture all the groups of non-whitespace characters only.

This is basically a reversal of the logic - instead of splitting at single white space characters, which can create “empty” elements in the result, you just match consecutive groups of non-WS characters - that way it doesn't matter any more if there's one or one hundred white space characters between them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM