[英]Check if String Contains a word or Substring in HTML using Javascript
Im trying to get the value of my admin textarea and check if the textarea of user have the substring or word that matches the admin value, when the user input 1 word and matches the admin it would say correct but when the user input a sentence with the correct word in admin it would say error instead of correct can you help pls我试图获取我的 admin textarea 的值并检查用户的 textarea 是否具有与 admin 值匹配的子字符串或单词,当用户输入 1 个单词并匹配 admin 时,它会说正确,但是当用户输入一个句子时管理中的正确词会说错误而不是正确的,你能帮忙吗
var a = document.getElementById('admin'); var b = document.getElementById('user'); function sample() { if (a.value.includes(b.value)) { document.getElementById('output').innerHTML = "USER INPUT WITH KEYWORD"; } else { document.getElementById('output').innerHTML = "USER INPUT WITHOUT KEYWORD"; } }
<textarea id="admin" placeholder="admin"></textarea> <textarea id="user" placeholder="user"></textarea> <textarea id="output"></textarea> <button style="height: 50px; width: 100px;" onclick="sample()"> </buttom>
As @Chris G said,正如@Chris G 所说,
Your code is checking if the user value is inside the admin value, not the other way around.
您的代码正在检查用户值是否在 admin 值内,而不是相反。 Instead of
a
andb
, use descriptive variable names to prevent basic mistakes like this.而不是
a
和b
,使用描述性变量名称来防止这样的基本错误。
In your code, you are checking if the admin value has the substring or word that matches the user value, but in your question, you wanted it the other way around.在您的代码中,您正在检查 admin 值是否具有与用户值匹配的子字符串或单词,但在您的问题中,您希望它反过来。 One simple way to prevent this mistake is by double checking your variables, or by putting in more descriptive names.
防止这种错误的一种简单方法是仔细检查变量,或者输入更具描述性的名称。 For example, instead of using
a
and b
as your variable names, use admin
and user
.例如,不要使用
a
和b
作为变量名,而是使用admin
和user
。
Corrected Code:更正的代码:
var a = document.getElementById('admin');
var b = document.getElementById('user');
function sample() {
if (b.value.includes(a.value)) {
document.getElementById('output').innerHTML = "USER INPUT WITH KEYWORD";
} else {
document.getElementById('output').innerHTML = "USER INPUT WITHOUT KEYWORD";
}
}
Corrected Code with better practices:使用更好的实践更正代码:
var admin = document.getElementById('admin');
var user = document.getElementById('user');
function sample() {
if (user.value.includes(admin.value)) {
document.getElementById('output').innerHTML = "USER INPUT WITH KEYWORD";
} else {
document.getElementById('output').innerHTML = "USER INPUT WITHOUT KEYWORD";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.