检查输入字段是否包含特定文本 [英] Check if input fields contains certain text

查看:80
本文介绍了检查输入字段是否包含特定文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查找用户输入到输入字段的内容是否包含某些文本 - 我有点工作,但只能用于完全匹配而不是部分匹配。如果用户在我匹配的文本之前键入任何内容,当然代码不会触发。

I'm trying to find if what the user typing in to an input field contain certain text - I've kinda got it works, but only working for an exact match as opposed to a partial match. If a user types anything before the text i'm matching, of course the code doesn't trigger.

我需要做的是检查输入是否包含<$输入字段中的所有c $ c> @ nyu.edu 。

What i need to do is check if the input contains @nyu.edu at all in the input field.

$('.email').keyup(function(){
    if ($(".email").val() == "@nyu.edu") {
        $("p.warning").css("visibility", "visible");
    }
    else if ($(".email").val() != "@nyu.edu") {
        $("p.warning").css("visibility", "hidden");
    }
});


推荐答案

检查字符串是否包含子字符串非常容易通过 haystack.indexOf(针)并检查 -1 (未找到)。

Checking if a string contains a substring is pretty easily done by taking haystack.indexOf(needle) and checking against -1 (not found).

if ($(".email").val().indexOf("@nyu.edu") !== -1) {
    // contains
} else {
    // does not contain
}






ES6 草案中有一个功能,您可能会发现它更自然,称为包括


There is a function in the ES6 draft which you may find more natural, called includes

您可以添加对 ES6的支持 String.prototype.includes 这样的

You can add support for ES6's String.prototype.includes like this

if (!String.prototype.includes) {
    String.prototype.includes = function (needle, pos) {
        return this.indexOf(needle, pos || 0) !== -1;
    };
}

"foobar".includes('foo'); // true

这篇关于检查输入字段是否包含特定文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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