简体   繁体   English

Javascript子字符串搜索

[英]Javascript sub-string search

Hi I have a basic text search for a div using an input box but I can only get it to work if I enter the exact full word, how would I modify this code to work for a sub-string eg if I enter Test I would like to return both Test and Test2 or Just T should return both etc? 嗨,我使用输入框对div进行了基本的文本搜索,但是只有输入完整的完整单词,我才能使它工作,如何修改此代码以用于子字符串,例如,如果输入Test,我会想同时返回Test和Test2还是Just T应该同时返回等等?

 //search site for pages function search_sitemap() { let input = document.getElementById('searchbar').value input=input.toLowerCase(); let x = document.getElementsByClassName('pages'); var urls = []; for (i = 0; i < x.length; i++) { // make an array of strings var words = x[i].innerHTML.toLowerCase().split(","); if (!words.includes(input)) { x[i].style.display="none"; } else { x[i].style.display = "block"; urls.push(x[i].href); } } return urls; } </script> 
 <!DOCTYPE html> <html> <head></head> <body> <header></header> <!--searchbar--> <button class="searchbtn"><img src="Images\\search.png" id="s-icon"> <div id='searchlist'> <a class="pages" href="test.html" style="display:none;">Test</a></li> <a class="pages" href="test2.html" style="display:none;">Test2</a></li> <a class="pages" href="best.html" style="display:none;">Best</a></li> <a class="pages" href="rest.html" style="display:none;">Rest</a></li> </div> </button> <div class="searchbar"> <input type="text" id="searchbar" onkeyup="search_sitemap()" placeholder="" value="Search.." maxlenght="25" autocomplete="off" onMouseDown="active();" onBlur="inactive()" /> </div> </div> </body> </html> 

您可以检查某些单词是否搜索开头

words.some(word => word.startsWith(input))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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