如何使用jQuery检查数组中的单词的文本字段值? [英] How do I check a text field value against words in an array using jQuery?

查看:43
本文介绍了如何使用jQuery检查数组中的单词的文本字段值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数组有字符串值:

var bannedWords = ["cat","dog","test"]

我的文本输入字段检查该值是否包含数组中的单词:

My text input field checks if the value contains words from the array:

var title = $j('#edit-content').val()
if ($j.inArray(title, bannedWords) != -1) { alert("it's inside the array") }

当值为cat时,它按预期工作。当值为猫是黑色时,我想要提醒,因为cat在输入值内。

When the value is "cat", it works as expected. When the value is "the cat is black", I want the alert because "cat" is inside the input value.

我明白为什么它不起作用,但是我不知道怎么办?
在值中有某种循环?

I understand why it doesn't work, but I don't know how can I do this? with some kind of loop in the value?

提前致谢!

推荐答案

你可以建立一个正则表达式并使用它来测试输入:

You could build a regular expression out of your array and use it to test the input:

// 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());

示例: http://jsfiddle.net/aZbWP/1

这篇关于如何使用jQuery检查数组中的单词的文本字段值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆