
在 web 开发中,经常需要根据用户的输入执行不同的操作。一个常见的场景是,根据用户在表单中输入的内容,判断其是否包含某些预定义的关键词,并根据判断结果执行相应的逻辑。本文将介绍如何使用 javascript 实现这一功能,重点是如何高效地判断用户输入是否包含关键词数组中的任何一个关键词,而不仅仅是完全匹配。
传统的 indexOf 方法要求用户输入的内容与关键词完全匹配,才能返回正确的结果。而 includes 方法则可以判断一个字符串是否包含另一个字符串,结合 filter 方法,可以实现关键词的模糊匹配。
以下是一个示例代码,演示了如何使用 filter 和 includes 方法判断用户输入是否包含关键词数组中的任何一个关键词:
var answer = 'I like climbing';
const hallasanKeyword = [
"hiking",
"climb",
"hike",
"outside",
];
const udoKeyword = [
"cycling",
"cycle",
"bike",
];
const lovelandKeyword = [
"art",
"fun",
"silly",
];
const cityKeyword = [
"nightlife",
"restaurant",
"eat",
];
if ((hallasanKeyword.filter(arItem => answer.includes(arItem))).length > 0) {
alert('scroll to hallasan')
} else if ((udoKeyword.filter(arItem => answer.includes(arItem))).length > 0) {
alert('scroll to udo')
} else if ((lovelandKeyword.filter(arItem => answer.includes(arItem))).length > 0) {
alert('scroll to loveland')
} else if ((cityKeyword.filter(arItem => answer.includes(arItem))).length > 0) {
alert('scroll to city')
} 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!"
);
}代码解释:
通过结合 filter 和 includes 方法,可以方便地判断用户输入是否包含关键词数组中的任何一个关键词。这种方法不仅简单易懂,而且具有很高的灵活性,可以根据实际需求进行定制。在实际开发中,可以根据具体情况选择合适的匹配方法,从而提高用户体验和程序的效率。
以上就是如何判断用户表单输入是否包含数组中的关键词?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号