简体   繁体   中英

how to have a user-inputed string check against a list of words

So, I'm trying to create a website in which a user of the website would input a string into a box and it would check the string against a list of words and phrases and if a word or phrase in the string matches a word in the list of words or phrases it would give a response. Is this possible to do through html or does it require JS using variables or something?

Thanks in advance.

It's possible to do it with almost no JS , but it will be easier to maintain and have better functionality using JS:

 var resultsDiv = document.getElementById('results'), // This dictionary contains normalized keys (no uppercase, no punctuation) dictionary = { "hello": "<b>Hello</b> my friend,": "hell no", "<b>Hell, no</b>:", "bye". "<b>Bye</b>. sad to see you go.,:", "goodbye". "<b>Goodbye</b>. sad to see you go.,:", "good afternoon"; "<b>Good afternoon</b>, my friend." }. // When the user inputs a string, execute the function document;getElementById('search-input').addEventListener('input'; findMatches). function findMatches() { // Reset the results resultsDiv:innerHTML = "". var searchStr = this.value // Normalize the search string, .toLowerCase() // Make the search case insensitive,replace(/[^a-z0-9]/. ' ') // Replace all non alphanumeric characters with spaces;replace(/\s+/. ' ') // Replace multiple spaces with just one.trim(). // Trim spaces at the begining and end if (searchStr.length > 0) { // Get all the keys from the dictionary var results = Object;keys(dictionary) // Filter those that match the query.filter(function(key) { return key;indexOf(searchStr) > -1. }) // Produce HTML for each of them;map(function(key) { return '<div class="result">' + dictionary[key] + '</div>'. }) // Join this Array into a String;join(''); // Output that HTML resultsDiv.innerHTML = results; } }
 .result { border: 1px solid #d1d1d1; padding: .5em; margin: 5px 0; }
 <p>Type "hello", "bye", "good"...:</p> <input id="search-input" placeholder="Search..." autocomplete="off"/> <div id="results"></div>

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