[英]How do I check for specific string within text input submitted by a user?
I am trying to write a vanilla JavaScript function that checks the user's text input for specific pieces of string that have been defined in an array.我正在尝试编写一个 vanilla JavaScript function 来检查用户的文本输入是否已在数组中定义了特定的字符串片段。 The string does not have to match exactly but at least one of the defined strings (in the array) must form at least part of the user text input.
该字符串不必完全匹配,但至少一个定义的字符串(在数组中)必须至少构成用户文本输入的一部分。
Essentially, a user will input a question and the function will check if the question is valid (ie contains question words such as how, why, when, etc.).本质上,用户将输入一个问题,function 将检查该问题是否有效(即包含诸如如何、为什么、何时等问题词)。
I have succeeded in partially achieving what I'm looking for using the indexOf() and includes() methods but they will only work when there is an exact match and not when one the question words (defined in the array) forms only part of the question submitted by the user.我已经成功地使用 indexOf() 和 includes() 方法部分实现了我正在寻找的东西,但它们仅在存在完全匹配时才起作用,而不是在一个问题词(在数组中定义)forms 只是一部分时起作用用户提交的问题。
My HTML我的 HTML
<div class="user-input">
<input type="text" class="form-control user-question" placeholder="What is your question?">
<button type="button" class="btn">Submit</button>
</div>
My JavaScript我的 JavaScript
const questionWords = [
'what',
'when',
'where',
'who',
'whom',
'which',
'whose',
'why',
'what',
'how',
'?'
]
let question = document.querySelector('.user-question');
let button = document.querySelector('.btn');
button.addEventListener('click', validQuestion);
function validQuestion() {
if (questionWords.indexOf(question.value) > -1) {
console.log('good question');
} else {
console.log('bad question');
}
};
includes() method包含() 方法
function validQuestion() {
if (questionWords.includes(question.value)) {
console.log('good question');
} else {
console.log('bad question');
}
};
I understand that the some() method may work but am having difficulty in applying it to my example above.我知道 some() 方法可能有效,但很难将其应用于我上面的示例。
I'd say try it with a RegExp我会说用 RegExp 试试
Note : You have to escape the?注意:你有越狱的? since it's a regex token too.
因为它也是一个正则表达式标记。
const questionWords = [ 'what', 'when', 'where', 'who', 'whom', 'which', 'whose', 'why', 'what', 'how', '\\?' ]; let question = document.querySelector('.user-question'); let button = document.querySelector('.btn'); button.addEventListener('click', validQuestion); function validQuestion() { if (new RegExp(`(${questionWords.join("|")})`, "gi").test(question.value)) { console.log('good question'); } else { console.log('bad question'); } };
<div class="user-input"> <input type="text" class="form-control user-question" placeholder="What is your question?"> <button type="button" class="btn">Submit</button> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.