本文介绍了如何使用 JavaScript 判断用户在表单中输入的内容是否包含预定义的关键词数组中的任意一个关键词。通过使用 Filter 和 includes 方法,可以有效地实现模糊匹配,从而提高用户体验,并引导用户浏览特定内容。本文提供了详细的代码示例和解释,帮助开发者轻松实现这一功能。
在 Web 开发中,经常需要根据用户的输入内容执行不同的操作。一个常见的场景是,根据用户输入的关键词,将页面滚动到特定的位置。如果需要匹配多个关键词,并且允许用户输入的内容包含关键词即可,而不需要完全匹配,可以使用以下方法。
实现原理
核心思想是使用数组的 filter 方法结合字符串的 includes 方法。filter 方法用于筛选出数组中满足条件的元素,includes 方法用于判断字符串是否包含指定的子字符串。
代码示例
以下是一个完整的代码示例,演示了如何判断用户输入是否包含关键词数组中的任意关键词:
function answerQuestion() { event.preventDefault(); var answer = document.getElementById("answer").value; answer = answer.toLowerCase(); answer = answer.trim(); const hallasanKeyword = [ "hiking", "climb", "hike", "outside", ]; const udoKeyword = [ "cycling", "cycle", "bike", ]; const lovelandKeyword = [ "art", "fun", "silly", ]; const cityKeyword = [ "nightlife", "restaurant", "eat", ]; if ((hallasanKeyword.filter(item => answer.includes(item))).length > 0) { var hallasan = document.getElementById("hallasan").offsetTop; window.scrollTo({ top: hallasan, behavior: "smooth" }); } else if ((udoKeyword.filter(item => answer.includes(item))).length > 0) { var udo = document.getElementById("udo").offsetTop; window.scrollTo({ top: udo, behavior: "smooth" }); } else if ((lovelandKeyword.filter(item => answer.includes(item))).length > 0) { var loveland = document.getElementById("loveland").offsetTop; window.scrollTo({ top: loveland, behavior: "smooth" }); } else if ((cityKeyword.filter(item => answer.includes(item))).length > 0) { var city = document.getElementById("city").offsetTop; window.scrollTo({ top: city, behavior: "smooth" }); } else { alert( "Sorry, what you typed in didn't match any of the keywords on our list! Try something else, or scroll through this page - you might find something you'd like!" ); } }
代码解释
- 获取用户输入: 首先,获取用户在表单中输入的内容,并将其转换为小写,并去除首尾空格,以便进行不区分大小写的匹配。
- 定义关键词数组: 定义包含关键词的数组,例如 hallasanKeyword、udoKeyword 等。
- 使用 filter 和 includes 进行匹配: 对于每个关键词数组,使用 filter 方法筛选出数组中包含在用户输入中的关键词。item => answer.includes(item) 是一个箭头函数,用于判断用户输入 answer 是否包含当前关键词 item。
- 判断是否匹配成功: 如果 filter 方法返回的数组的长度大于 0,则表示匹配成功,执行相应的操作,例如将页面滚动到特定的位置。
- 处理未匹配的情况: 如果所有关键词数组都未匹配成功,则显示提示信息。
注意事项
- 大小写处理: 在进行匹配之前,将用户输入和关键词都转换为小写,可以避免大小写敏感的问题。
- 空格处理: 使用 trim() 方法去除用户输入首尾的空格,可以提高匹配的准确性。
- 性能优化: 如果关键词数组非常大,可以考虑使用更高效的算法,例如使用正则表达式进行匹配。
总结
通过使用 filter 和 includes 方法,可以方便地判断用户输入是否包含关键词数组中的任意关键词。这种方法简单易懂,并且能够满足大多数应用场景的需求。在实际开发中,可以根据具体情况进行适当的调整和优化。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END