Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
465 views
in Technique[技术] by (71.8m points)

javascript - Check if input fields contains certain text

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.

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");
    }
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

There is a function in the ES6 draft which you may find more natural, called 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...