我的数组有字符串值:
var bannedWords = ["cat","dog","test"]
我的文本输入字段检查该值是否包含数组中的单词:
var title = $j('#edit-content').val()
if ($j.inArray(title, bannedWords) != -1) { alert("it's inside the array") }
当值为“cat”时,它按预期工作。当值为“the cat is black”时,我想要警报,因为“cat”在输入值内。
我明白为什么它不起作用,但我不知道我该怎么做? 在值中有某种循环?
提前致谢!
最佳答案
你可以构建一个 regular expression从你的数组中取出并用它来测试输入:
// The 'i' flag matches values regardless of case.
var regex = new RegExp('\\b' + bannedWords.join("\\b|\\b") + '\\b', 'i');
// Regex would equal /\bcat\b|\bdog\b|\btest\b/i
var valid = !regex.test($("#edit-content").val());
关于javascript - 如何使用 jQuery 根据数组中的单词检查文本字段值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14242722/